Batter up

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.

The data

Let’s load up the data for the 2011 season.

download.file("http://www.openintro.org/stat/data/mlb11.RData", destfile = "mlb11.RData")
load("mlb11.RData")
head(mlb11)
##                  team runs at_bats hits homeruns bat_avg strikeouts
## 1       Texas Rangers  855    5659 1599      210   0.283        930
## 2      Boston Red Sox  875    5710 1600      203   0.280       1108
## 3      Detroit Tigers  787    5563 1540      169   0.277       1143
## 4  Kansas City Royals  730    5672 1560      129   0.275       1006
## 5 St. Louis Cardinals  762    5532 1513      162   0.273        978
## 6       New York Mets  718    5600 1477      108   0.264       1085
##   stolen_bases wins new_onbase new_slug new_obs
## 1          143   96      0.340    0.460   0.800
## 2          102   90      0.349    0.461   0.810
## 3           49   95      0.340    0.434   0.773
## 4          153   71      0.329    0.415   0.744
## 5           57   90      0.341    0.425   0.766
## 6          130   77      0.335    0.391   0.725

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.

  1. What type of plot would you use to display the relationship between runs and one of the other numerical variables? Plot this relationship using the variable at_bats as the predictor. Does the relationship look linear?

    In order to check the relationships between the variables “runs” and “at_bats” I would use scatterplot.

plot(mlb11$runs ~ mlb11$at_bats,
     xlab = "At Bats",             
     ylab = "Runs",
     main = "Relationships between the variables 'runs' and 'at_bats'")  

I would say that the relationships between the variables ‘runs’ and ‘at_bats’ can be classified as linear (but not perfectly linear) rather than non-linear.

If you knew a team’s at_bats, would you be comfortable using a linear model to predict the number of runs?

Since the relationships between the variables ‘runs’ and ‘at_bats’ are not perfectly linear(as most of the dots won’t fall on imaginary regression line) we will be able predict the number of runs with a certain accuracy using a linear model.

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

Sum of squared residuals

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.

  1. Looking at your plot from the previous exercise, describe the relationship between these two variables. Make sure to discuss the form, direction, and strength of the relationship as well as any unusual observations.

The plot has a positive linear relationships as it travels upwards from left to right. It shows a steady rate of increase. The relationship between runs and at bats are linear but not perfectly linear because most of dots deviates from imaginary regression line. Also, the relationship between runs and at bats can be considered moderately strong since the correlation coefficient is greater than 0.5. The plot contains some positive outliers (the dots that deviates from imaginary regression line more than the others).

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.

  1. Using 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?

    I ran the function plot_ssseveral times and got similar result. The smallest sum of squares is 123721.9.

The linear model

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.

  1. Fit a new model that uses 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?

Let’s build a linear model of homeruns as a function of at_bats.

m2 <- lm(homeruns ~ at_bats, data = mlb11)
summary(m2)
## 
## Call:
## lm(formula = homeruns ~ at_bats, data = mlb11)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -69.231 -25.264   5.451  20.379  71.189 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)  
## (Intercept) -774.87323  430.90463  -1.798   0.0829 .
## at_bats        0.16776    0.07801   2.151   0.0403 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 33.55 on 28 degrees of freedom
## Multiple R-squared:  0.1418, Adjusted R-squared:  0.1111 
## F-statistic: 4.625 on 1 and 28 DF,  p-value: 0.04029

Based on R output we can write down the least squares regression line for the linear model of homeruns as a function of at_bats.:

\[ \hat{y} = -774.87323 + 0.16776 * atbats \]

In this case, the slope of a regression line represents the rate of change in homeruns as at_bats changes. A single increase in at_bats increases homeruns by 0.16776.

Prediction and prediction errors

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.

  1. If a team manager saw the least squares regression line and not the actual data, how many runs would he or she predict for a team with 5,578 at-bats?
at_bats <- 5578
runs_predicted <- -2789.2429 + 0.6305 * at_bats 
round(runs_predicted, 0)
## [1] 728
The predicted number of runs is 728. 

Is this an overestimate or an underestimate, and by how much? In other 
words, what is the residual for this prediction?

Let's find the actual number of runs.
#load dplyr package
library(dplyr)

#order at_bats
mlb11_sorted <- mlb11 %>% arrange(-at_bats)
head(mlb11_sorted,10)
##                     team runs at_bats hits homeruns bat_avg strikeouts
## 1         Boston Red Sox  875    5710 1600      203   0.280       1108
## 2     Kansas City Royals  730    5672 1560      129   0.275       1006
## 3          Texas Rangers  855    5659 1599      210   0.283        930
## 4        Cincinnati Reds  735    5612 1438      183   0.256       1250
## 5          New York Mets  718    5600 1477      108   0.264       1085
## 6         Houston Astros  615    5598 1442       95   0.258       1164
## 7      Baltimore Orioles  708    5585 1434      191   0.257       1120
## 8  Philadelphia Phillies  713    5579 1409      153   0.253       1024
## 9         Detroit Tigers  787    5563 1540      169   0.277       1143
## 10     Toronto Blue Jays  743    5559 1384      186   0.249       1184
##    stolen_bases wins new_onbase new_slug new_obs
## 1           102   90      0.349    0.461   0.810
## 2           153   71      0.329    0.415   0.744
## 3           143   96      0.340    0.460   0.800
## 4            97   79      0.326    0.408   0.734
## 5           130   77      0.335    0.391   0.725
## 6           118   56      0.311    0.374   0.684
## 7            81   69      0.316    0.413   0.729
## 8            96  102      0.323    0.395   0.717
## 9            49   95      0.340    0.434   0.773
## 10          131   81      0.317    0.413   0.730

None of the teams has 5,578 at-bats. However, the team “Philadelphia Phillies” has 5,578 at-bats. According to the table, 5,578 at-bats correspond to 713 runs.

Since the predicted number of runs is greater than actual number of runs we can conclude that the predicted number of runs is overestimate by 728-713 = 15 runs.

Model diagnostics

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

  1. Is there any apparent pattern in the residuals plot? What does this indicate about the linearity of the relationship between runs and at-bats?

    A residual plot is typically used to find problems with regression. These problems are more easily seen with a residual plot than by looking at a plot of the original data set. Ideally, residuals values should be equally and randomly spaced around the horizontal axis.

    By looking at the residuals plot above we can conclude that the relationships between residuals and at-bats is linear since residual values pretty equally and randomly spaced around the horizontal axis on the residual plot.

Nearly normal residuals: To check this condition, we can look at a histogram

hist(m1$residuals)

summary(m1$residuals)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -125.58  -47.05  -16.59    0.00   54.40  176.87

or a normal probability plot of the residuals.

qqnorm(m1$residuals)
qqline(m1$residuals)  # adds diagonal line to the normal prob plot

  1. Based on the histogram and the normal probability plot, does the nearly normal residuals condition appear to be met?

    By looking at the histogram we can say that the distribution of residuals is unimodel since it has one clear peak. It’s not symmetric and it’s right skewed as mean is greater than the median. However, by looking at normal probability plot we can see that most of the dots don’t deviate much from the line. Moreover, distribution doesn’t contain outliers. So that, we can conclude that distribution of residual is close to normal distribution. It means that the nearly normal residuals condition appear to be met.

Constant variability:

  1. Based on the plot in (1), does the constant variability condition appear to be met?

    I would say that the constant variability condition appear to be met as the variability of points around the least squares line is reasonably constant while the variability of residuals around the zero line look reasonably constant as well.


On Your Own

plot(mlb11$runs ~ mlb11$hits,
     xlab = "Hits",             
     ylab = "Runs",
     main = "Relationships between the variables 'runs' and 'hits'")  
m3 <- lm(runs ~ hits, data = mlb11)
abline(m3)

The plot has a positive linear relationship as it travels upwards from left to right. It shows a steady rate of increase. The relationships between runs and hits are linear but not perfectly linear because most of dots deviates from the regression line. Also, the relationship between runs and hits can be considered moderately strong since the correlation coefficient is greater than 0.5. The plot contains one positive outliers (the dot that deviates from the regression line more than the others).

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
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

As R\(^2\) value of the linear model of runs and hits is higher than R\(^2\) value of the linear model of runs and at_bats we can say that in the linear model of runs and hits the data are closer to the fitted regression line. So, we can conclude that the variable runs predicts runs better that the variable at_bats.

#create variables column
variables <- c(colnames(mlb11)[4:9])

#create correlation column
correlation <- c(cor(mlb11$runs,mlb11$hits),
cor(mlb11$runs,mlb11$homeruns),
cor(mlb11$runs,mlb11$bat_avg),
cor(mlb11$runs,mlb11$strikeouts),
cor(mlb11$runs,mlb11$stolen_bases),
cor(mlb11$runs,mlb11$wins))

cor_table <- data.frame(variables,correlation)
cor_table[order(-correlation),]
##      variables correlation
## 3      bat_avg  0.80998589
## 1         hits  0.80121081
## 2     homeruns  0.79155769
## 6         wins  0.60080877
## 5 stolen_bases  0.05398141
## 4   strikeouts -0.41153120

By looking at the correlation table we can say that all variables except strikeouts are strongly correlated with runs. The correlation coefficient of the variables bat_avg and hits are higher that the correlation coefficient of other variables.

Let’s plot the relationship between runs and hits and the relationships between runs and bat_avg.

plot(mlb11$runs ~ mlb11$hits,
     xlab = "Hits",             
     ylab = "Runs",
     main = "Relationships between the variables 'runs' and 'hits'")  
abline(m3)

plot(mlb11$runs ~ mlb11$bat_avg,
     xlab = "Bat_avg",             
     ylab = "Runs",
     main = "Relationships between the variables 'runs' and 'bat_avg'")  
m4 <- lm(runs ~ bat_avg, data = mlb11)
abline(m4)

Both plots have a positive linear relationship as they travels upwards from left to right. The relationships between variables are linear but not perfectly linear because most of dots deviates from the regression line. Also, the relationship between runs and hits and the relationships between runs and average bats can be considered strong since the correlation coefficients are greater than 0.5 in both cases. Both plots contain positive outliers (the dot that deviates from the regression line more than the others).

It’s really hard to say which variables better predicts runs just by looking at the plot.

In order to figure out which variables better predicts runs we have to find R\(^2\) value of the linear model of runs and hits and the linear model of runs and bat_avg.

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
summary(m4)
## 
## 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

Since R\(^2\) value of the linear model of runs and bat_avg is higher than R\(^2\) value of the linear model of runs and hits we can say that in the linear model of runs and bat_avg the data are closer to the fitted regression line. So, we can conclude that the variable bat_avg predicts runs better that the variable hits.

By looking at the correlation table we can state that new variables are more strongly correlated with the variable runs that the old variables since their correlation coefficients are higher.

In order to prove our finding let’s calculate R\(^2\) value of the linear model of runs and new_onbase, the linear model of runs and new_slug and the linear model of runs and new_obs.

m5 <- lm(runs ~ new_onbase, data = mlb11)
m6 <- lm(runs ~ new_slug, data = mlb11)
m7 <- lm(runs ~ new_obs, data = mlb11)

#let's include the old variables that have the higher r-square values among all old variables.  We already figured out that those variables are `hits` and `bat_avg` 
linear_models <- c("run ~ hits","run ~ bat_avg","runs ~ new_onbase","runs ~ new_slug","runs ~ new_obs")
r_squared <- c(summary(m3)$r.squared,summary(m4)$r.squared ,summary(m5)$r.squared ,summary(m6)$r.squared ,summary(m7)$r.squared )
adj.r.squared <- c(summary(m3)$adj.r.squared,summary(m4)$adj.r.squared ,summary(m5)$adj.r.squared ,summary(m6)$adj.r.squared ,summary(m7)$adj.r.squared )

r2_tables <- data.frame(linear_models,r_squared,adj.r.squared)
r2_tables[order(-adj.r.squared),]
##       linear_models r_squared adj.r.squared
## 5    runs ~ new_obs 0.9349271     0.9326031
## 4   runs ~ new_slug 0.8968704     0.8931872
## 3 runs ~ new_onbase 0.8491053     0.8437162
## 2     run ~ bat_avg 0.6560771     0.6437942
## 1        run ~ hits 0.6419388     0.6291509

By looking at R\(^2\) table we can conclude that R\(^2\) values of new variables are higher that R\(^2\) values of the old variables. It means that new variables predict runs better than the old variables. The variable new_obs has the higher R\(^2\) value among all variables. It means that the variable new_obs predict runs better than the other variables.

Let’s start with verifying linearity. We should check whether the relationship between residuals and hits are linear.

plot(m7$residuals ~ mlb11$new_obs)
abline(h = 0, lty = 3)  # adds a horizontal dashed line at y = 0

By looking at the residuals plot above we can conclude that the relationships between residuals and hits are linear since residuals values pretty equally and randomly spaced around the horizontal axis on the residual plot.

Now let’s investigate whether residuals distribution is near normal or not. To check this condition, we can look at a histogram

hist(m7$residuals)

summary(m7$residuals)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -43.456 -13.690   1.165   0.000  13.935  41.156
qqnorm(m7$residuals)
qqline(m7$residuals)  # adds diagonal line to the normal prob plot

By looking at the histogram we can say that the distribution of residuals is unimodel since it has one clear peak. It’s not symmetric and it’s right skewed as mean is greater than the median. However, by looking at normal probability plot we can see that most of the dots don’t deviate much from the line. Moreover, distribution doesn’t contain outliers. So that, we can conclude that distribution of residual is close to normal distribution. It means that the nearly normal residuals condition appear to be met.

The last condition that we have to check is constant variability.

I would say that the constant variability condition appear to be met as the variability of points around the least squares line is reasonably constant while the variability of residuals around the zero line look reasonably constant as well.

So, the regression model satisfies all three conditions.

This is a product of OpenIntro that is released under a Creative Commons Attribution-ShareAlike 3.0 Unported. This lab was adapted for OpenIntro by Andrew Bray and Mine Çetinkaya-Rundel from a lab written by the faculty and TAs of UCLA Statistics.