The movie Moneyball focuses on the “quest for the secret of success in baseball”. It follows a low-budget team, the Oakland Athletics, who believed that underused statistics, such as a player’s ability to get on base, betterpredict the ability to score runs than typical statistics like home runs, RBIs (runs batted in), and batting average. Obtaining players who excelled in these underused statistics turned out to be much more affordable for the team.
In this lab we’ll be looking at data from all 30 Major League Baseball teams and examining the linear relationship between runs scored in a season and a number of other player statistics. Our aim will be to summarize these relationships both graphically and numerically in order to find which variable, if any, helps us best predict a team’s runs scored in a season.
library(tidyverse)## ── Attaching packages ────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.1.0 ✔ purrr 0.3.0
## ✔ tibble 2.1.1 ✔ dplyr 0.8.0.1
## ✔ tidyr 0.8.2 ✔ stringr 1.4.0
## ✔ readr 1.3.1 ✔ forcats 0.4.0
## ── Conflicts ───────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(kableExtra)##
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
##
## group_rows
Let’s load up the data for the 2011 season.
load("more/mlb11.RData")In addition to runs scored, there are seven traditionally used variables in the data set: at-bats, hits, home runs, batting average, strikeouts, stolen bases, and wins. There are also three newer variables: on-base percentage, slugging percentage, and on-base plus slugging. For the first portion of the analysis we’ll consider the seven traditional variables. At the end of the lab, you’ll work with the newer variables on your own.
runs and one of the other numerical variables? Plot this relationship using the variable at_bats as the predictor. Does the relationship look linear? If you knew a team’s at_bats, would you be comfortable using a linear model to predict the number of runs?(Alexander Ng’s Response)
I would use a scatterplot to assess the relationship between runs and other numerical variables. ggplot2 allows us to see the result easily. The relationship appears linear and positively correlated.
However, due to the wide dispersion, the ability to predict a team’s runs based solely on its at_bats is problematic. I would not do it. One reason is that low correlation between at_bats and runs means that for a given level or narrow range of the predictor (say 5500 at bats) the associated range of values for runs is widely dispersed. Consider the 5 teams whose at_bats range between 5500 and 5525. The Florida Marlins ranked the worst of this cohort with 5508 at_bats and 625 runs. By contrast, the New York Yankees had 5518 at_bats (virtually the same) but had 867 runs (142 more than the Florida Marlins). This difference is significant.
ggplot(data = mlb11, aes( x = at_bats, y = runs, color = team ) ) + geom_point() + ggtitle("Runs vs At-Bats")mlb11 %>% filter( at_bats > 5500 & at_bats < 5525) %>% select( team, at_bats, runs ) %>% arrange( runs ) %>% kable()| team | at_bats | runs |
|---|---|---|
| Florida Marlins | 5508 | 625 |
| Chicago White Sox | 5502 | 654 |
| Los Angeles Angels | 5513 | 667 |
| Cleveland Indians | 5509 | 704 |
| New York Yankees | 5518 | 867 |
If the relationship looks linear, we can quantify the strength of the relationship with the correlation coefficient.
cor(mlb11$runs, mlb11$at_bats)## [1] 0.610627
Think back to the way that we described the distribution of a single variable. Recall that we discussed characteristics such as center, spread, and shape. It’s also useful to be able to describe the relationship of two numerical variables, such as runs and at_bats above.
(Alexander Ng’s Response) The relationship between the variable is: positively related (slope of scatterplot is positive), loosely correlated ( the R-squared is only 61%), and there is significant spread in the runs data. Two outliers are the New York Yankees with 867 runs and the Houston Astros with 615 runs.
mlb11 %>% filter( runs == 615 | runs == 867) %>% select(team, at_bats, runs ) %>% kable()| team | at_bats | runs |
|---|---|---|
| New York Yankees | 5518 | 867 |
| Houston Astros | 5598 | 615 |
Just as we used the mean and standard deviation to summarize a single variable, we can summarize the relationship between these two variables by finding the line that best follows their association. Use the following interactive function to select the line that you think does the best job of going through the cloud of points.
plot_ss(x = mlb11$at_bats, y = mlb11$runs)## Click two points to make a line.
## Call:
## lm(formula = y ~ x, data = pts)
##
## Coefficients:
## (Intercept) x
## -2789.2429 0.6305
##
## Sum of Squares: 123721.9
After running this command, you’ll be prompted to click two points on the plot to define a line. Once you’ve done that, the line you specified will be shown in black and the residuals in blue. Note that there are 30 residuals, one for each of the 30 observations. Recall that the residuals are the difference between the observed values and the values predicted by the line:
\[ e_i = y_i - \hat{y}_i \]
The most common way to do linear regression is to select the line that minimizes the sum of squared residuals. To visualize the squared residuals, you can rerun the plot command and add the argument showSquares = TRUE.
plot_ss(x = mlb11$at_bats, y = mlb11$runs, showSquares = TRUE)## Click two points to make a line.
## Call:
## lm(formula = y ~ x, data = pts)
##
## Coefficients:
## (Intercept) x
## -2789.2429 0.6305
##
## Sum of Squares: 123721.9
Note that the output from the plot_ss function provides you with the slope and intercept of your line as well as the sum of squares.
plot_ss, choose a line that does a good job of minimizing the sum of squares. Run the function several times. What was the smallest sum of squares that you got? How does it compare to your neighbors?(Alexander Ng’s Response)
I ran the function 6 times producing a table with the following values of SS, x (slope), and intercept. The last one was the best result obtained with the smallest sum of squares at 123,832.1. There is no obvious way to archive the mouse-click chosen line or sum of squares, so values are written down and imported to a data frame.
df = data.frame(x = c( .97, .5819, 0.3063, .8234, .77, .6117),
intercept = c( -4663, -2499, -974, -3836, -3549, -2683.63) ,
sumSquared = c( 145054, 137457, 160169, 140178, 130441.8, 123832.1) )
df %>% arrange(desc(sumSquared)) %>% kable() %>% kableExtra::kable_styling(bootstrap_options = c("striped", "hovering")
)| x | intercept | sumSquared |
|---|---|---|
| 0.3063 | -974.00 | 160169.0 |
| 0.9700 | -4663.00 | 145054.0 |
| 0.8234 | -3836.00 | 140178.0 |
| 0.5819 | -2499.00 | 137457.0 |
| 0.7700 | -3549.00 | 130441.8 |
| 0.6117 | -2683.63 | 123832.1 |
It is rather cumbersome to try to get the correct least squares line, i.e. the line that minimizes the sum of squared residuals, through trial and error. Instead we can use the lm function in R to fit the linear model (a.k.a. regression line).
m1 <- lm(runs ~ at_bats, data = mlb11)The first argument in the function lm is a formula that takes the form y ~ x. Here it can be read that we want to make a linear model of runs as a function of at_bats. The second argument specifies that R should look in the mlb11 data frame to find the runs and at_bats variables.
The output of lm is an object that contains all of the information we need about the linear model that was just fit. We can access this information using the summary function.
summary(m1)##
## Call:
## lm(formula = runs ~ at_bats, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -125.58 -47.05 -16.59 54.40 176.87
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -2789.2429 853.6957 -3.267 0.002871 **
## at_bats 0.6305 0.1545 4.080 0.000339 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 66.47 on 28 degrees of freedom
## Multiple R-squared: 0.3729, Adjusted R-squared: 0.3505
## F-statistic: 16.65 on 1 and 28 DF, p-value: 0.0003388
Let’s consider this output piece by piece. First, the formula used to describe the model is shown at the top. After the formula you find the five-number summary of the residuals. The “Coefficients” table shown next is key; its first column displays the linear model’s y-intercept and the coefficient of at_bats. With this table, we can write down the least squares regression line for the linear model:
\[ \hat{y} = -2789.2429 + 0.6305 * atbats \]
One last piece of information we will discuss from the summary output is the Multiple R-squared, or more simply, \(R^2\). The \(R^2\) value represents the proportion of variability in the response variable that is explained by the explanatory variable. For this model, 37.3% of the variability in runs is explained by at-bats.
homeruns to predict runs. Using the estimates from the R output, write the equation of the regression line. What does the slope tell us in the context of the relationship between success of a team and its home runs?(Alexander Ng’s Response)
Using the OLS regression fit, we see that the equation for the model is:
\[runs = 1.8345* (homeRuns) + 415.2389\] The slope tells us that for each additional homerun scored, the team gains 1.83 runs (on average). The slope is positive, so the more homeruns scored, the successful is the team (as measured in runs).
m2 = lm( runs ~ homeruns, data = mlb11)
summary(m2)##
## Call:
## lm(formula = runs ~ homeruns, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -91.615 -33.410 3.231 24.292 104.631
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 415.2389 41.6779 9.963 1.04e-10 ***
## homeruns 1.8345 0.2677 6.854 1.90e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 51.29 on 28 degrees of freedom
## Multiple R-squared: 0.6266, Adjusted R-squared: 0.6132
## F-statistic: 46.98 on 1 and 28 DF, p-value: 1.9e-07
ggplot(data=mlb11, aes(x=homeruns, y=runs) ) + geom_point() + ggtitle("Runs vs HomeRuns for MLB") +
geom_abline(intercept = m2$coefficients[1], slope = m2$coefficients[2], color="red")Let’s create a scatterplot with the least squares line laid on top.
plot(mlb11$runs ~ mlb11$at_bats)
abline(m1)The function abline plots a line based on its slope and intercept. Here, we used a shortcut by providing the model m1, which contains both parameter estimates. This line can be used to predict \(y\) at any value of \(x\). When predictions are made for values of \(x\) that are beyond the range of the observed data, it is referred to as extrapolation and is not usually recommended. However, predictions made within the range of the data are more reliable. They’re also used to compute the residuals.
(Alexander Ng’s Response)
There is no team with exactly 5578 at-bats. However, the Philadelphia Phillies had 5579 at-bats (the closest) and we use their data to esimate the residual. The predicted value is 728.59. The residual is -15.59. Thus, the model overestimates the number of runs relative to the actual runs by 15.59 runs.
mlb11 %>% arrange(at_bats) %>% select(team, at_bats, runs) %>%
filter( at_bats > 5570 & at_bats < 5580) %>%
mutate( residual = m1$residuals[16],
fittedvalue = m1$fitted.values[16] ) %>%
kable() %>% kable_styling()| team | at_bats | runs | residual | fittedvalue |
|---|---|---|---|---|
| Philadelphia Phillies | 5579 | 713 | -15.59552 | 728.5955 |
To assess whether the linear model is reliable, we need to check for (1) linearity, (2) nearly normal residuals, and (3) constant variability.
Linearity: You already checked if the relationship between runs and at-bats is linear using a scatterplot. We should also verify this condition with a plot of the residuals vs. at-bats. Recall that any code following a # is intended to be a comment that helps understand the code but is ignored by R.
plot(m1$residuals ~ mlb11$at_bats)
abline(h = 0, lty = 3) # adds a horizontal dashed line at y = 0(Alexander Ng’s Response)
The residuals plot vs. at_bats don’t show seasonality, trend or heteroskedasticity which is good. However, the range of residuals values is large for positive residuals than negative residuals. This is supported by the histogram plot where we see a right skew in the distribution.
This could be driven by one outlier (the New York Yankees). However, the pattern looks linear even with the outlier.
Nearly normal residuals: To check this condition, we can look at a histogram
hist(m1$residuals)or a normal probability plot of the residuals.
qqnorm(m1$residuals)
qqline(m1$residuals) # adds diagonal line to the normal prob plot(Alexander Ng’s Response)
Based on the qqnorm plot and histogram, the nearly normal residuals condition appears to be met.
Constant variability:
(Alexander Ng’s Response)
Based on the shape of the histogram and the pattern of residuals vs. at_bats scatterplot, the constant variability condition holds.
mlb11 that you think might be a good predictor of runs. Produce a scatterplot of the two variables and fit a linear model. At a glance, does there seem to be a linear relationship?(Alexander Ng’s response)
I consider the relationship between runs and hits in a linear model. I expect the number of hits to be a good predictor of the number of runs since a hit is a prerequisite for a run. Moreover, the correlation of their values is high at 80%.
ggplot(data=mlb11, aes( x = hits, y = runs) ) + geom_point() + ggtitle("Runs vs. Hits for MLB")cor(mlb11$hits, mlb11$runs)## [1] 0.8012108
runs and at_bats? Use the R\(^2\) values from the two model summaries to compare. Does your variable seem to predict runs better than at_bats? How can you tell?(Alexander Ng’s Response)
The relationship between runs and hits is stronger (as measured by higher correlation) than between runs and at_bats. The table below shows that runs vs hits has 64% R-squared versus runs vs. at_bats which has only a 37% R-squared.
m3 = lm( runs ~ hits, data=mlb11)
summary(m3)##
## Call:
## lm(formula = runs ~ hits, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -103.718 -27.179 -5.233 19.322 140.693
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -375.5600 151.1806 -2.484 0.0192 *
## hits 0.7589 0.1071 7.085 1.04e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 50.23 on 28 degrees of freedom
## Multiple R-squared: 0.6419, Adjusted R-squared: 0.6292
## F-statistic: 50.2 on 1 and 28 DF, p-value: 1.043e-07
df = data.frame( Model = c("At_bats", "Hits"),
Rsquared = c( summary(m1)$r.squared,
summary(m3)$r.squared )
)
df %>% kable() %>% kable_styling()| Model | Rsquared |
|---|---|
| At_bats | 0.3728654 |
| Hits | 0.6419388 |
runs and each of the other five traditional variables. Which variable best predicts runs? Support your conclusion using the graphical and numerical methods we’ve discussed (for the sake of conciseness, only include output for the best variable, not all five).m_batavg = lm( runs ~ bat_avg, data=mlb11)
m_homeruns = lm( runs ~ homeruns, data=mlb11)
m_strikeouts = lm( runs ~ strikeouts, data=mlb11)
m_stolenbases = lm( runs ~ stolen_bases, data=mlb11 )
m_wins = lm( runs ~ wins, data=mlb11 )
s_batavg = summary(m_batavg)
s_homeruns = summary(m_homeruns)
s_strikeouts = summary(m_strikeouts)
s_stolenbases = summary(m_stolenbases)
s_wins = summary(m_wins)
s_batavg##
## Call:
## lm(formula = runs ~ bat_avg, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -94.676 -26.303 -5.496 28.482 131.113
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -642.8 183.1 -3.511 0.00153 **
## bat_avg 5242.2 717.3 7.308 5.88e-08 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 49.23 on 28 degrees of freedom
## Multiple R-squared: 0.6561, Adjusted R-squared: 0.6438
## F-statistic: 53.41 on 1 and 28 DF, p-value: 5.877e-08
We see that batting average has the highest R-squared and highest F-statistic for predicting runs in a linear model of the tradition variables. The plots below shows the regression has a reasonable fit but there is one outlier. The outlier team is New York Yankees.
ggplot( data=mlb11, aes(x= bat_avg, y = runs)) + geom_point() +
geom_abline(intercept = m_batavg$coefficients[1],
slope = m_batavg$coefficients[2] ,
color = "red" ) +
ggtitle("Runs Vs. Batting Average from MLB")ggplot( data=m_batavg, aes( x= m_batavg$model$bat_avg, y = m_batavg$residuals) ) +
geom_point()hist(m_batavg$residuals)runs? Using the limited (or not so limited) information you know about these baseball statistics, does your result make sense?m_new_onbase = lm( runs ~ new_onbase, data=mlb11)
(s_new_onbase = summary(m_new_onbase) )##
## Call:
## lm(formula = runs ~ new_onbase, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -58.270 -18.335 3.249 19.520 69.002
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1118.4 144.5 -7.741 1.97e-08 ***
## new_onbase 5654.3 450.5 12.552 5.12e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 32.61 on 28 degrees of freedom
## Multiple R-squared: 0.8491, Adjusted R-squared: 0.8437
## F-statistic: 157.6 on 1 and 28 DF, p-value: 5.116e-13
m_new_slug = lm( runs ~ new_slug, data=mlb11)
(s_new_slug = summary(m_new_slug))##
## Call:
## lm(formula = runs ~ new_slug, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -45.41 -18.66 -0.91 16.29 52.29
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -375.80 68.71 -5.47 7.70e-06 ***
## new_slug 2681.33 171.83 15.61 2.42e-15 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 26.96 on 28 degrees of freedom
## Multiple R-squared: 0.8969, Adjusted R-squared: 0.8932
## F-statistic: 243.5 on 1 and 28 DF, p-value: 2.42e-15
m_new_obs = lm( runs ~ new_obs, data=mlb11)
(s_new_obs = summary(m_new_obs))##
## Call:
## lm(formula = runs ~ new_obs, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -43.456 -13.690 1.165 13.935 41.156
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -686.61 68.93 -9.962 1.05e-10 ***
## new_obs 1919.36 95.70 20.057 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 21.41 on 28 degrees of freedom
## Multiple R-squared: 0.9349, Adjusted R-squared: 0.9326
## F-statistic: 402.3 on 1 and 28 DF, p-value: < 2.2e-16
Clearl, the new variable that best fits a linear model as an explanatory variable is the new_obs variable since it has a R-squared of 93.4%. However, all the 3 variables are superior to the best of the traditional variables when measured by their R-squared.
(Alexander Ng’s Response)
We can see the diagnostics show the are relatively few issues with normality, heteroskedacity. Even the outlier of Yankee’s appears to be resolved. The results are suggestive that these variables provide explanatory power that can resolve the past outlier teams and normal teams jointly.
par(mfrow=c(2,2))
plot(m_new_obs)par(mfrow=c(1,1))
plot( mlb11$new_obs, mlb11$runs)
abline(m_new_obs)