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, better predict 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.

Libraries

library(tidyverse)
## -- Attaching packages ---------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.1.0     v purrr   0.2.5
## v tibble  1.4.2     v dplyr   0.7.7
## v tidyr   0.8.2     v stringr 1.3.1
## v readr   1.1.1     v forcats 0.3.0
## -- Conflicts ------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

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

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.

glimpse(mlb11)
## Observations: 30
## Variables: 12
## $ team         <fct> Texas Rangers, Boston Red Sox, Detroit Tigers, Ka...
## $ runs         <int> 855, 875, 787, 730, 762, 718, 867, 721, 735, 615,...
## $ at_bats      <int> 5659, 5710, 5563, 5672, 5532, 5600, 5518, 5447, 5...
## $ hits         <int> 1599, 1600, 1540, 1560, 1513, 1477, 1452, 1422, 1...
## $ homeruns     <int> 210, 203, 169, 129, 162, 108, 222, 185, 163, 95, ...
## $ bat_avg      <dbl> 0.283, 0.280, 0.277, 0.275, 0.273, 0.264, 0.263, ...
## $ strikeouts   <int> 930, 1108, 1143, 1006, 978, 1085, 1138, 1083, 120...
## $ stolen_bases <int> 143, 102, 49, 153, 57, 130, 147, 94, 118, 118, 81...
## $ wins         <int> 96, 90, 95, 71, 90, 77, 97, 96, 73, 56, 69, 82, 7...
## $ new_onbase   <dbl> 0.340, 0.349, 0.340, 0.329, 0.341, 0.335, 0.343, ...
## $ new_slug     <dbl> 0.460, 0.461, 0.434, 0.415, 0.425, 0.391, 0.444, ...
## $ new_obs      <dbl> 0.800, 0.810, 0.773, 0.744, 0.766, 0.725, 0.788, ...
summary(mlb11)
##                    team         runs          at_bats          hits     
##  Arizona Diamondbacks: 1   Min.   :556.0   Min.   :5417   Min.   :1263  
##  Atlanta Braves      : 1   1st Qu.:629.0   1st Qu.:5448   1st Qu.:1348  
##  Baltimore Orioles   : 1   Median :705.5   Median :5516   Median :1394  
##  Boston Red Sox      : 1   Mean   :693.6   Mean   :5524   Mean   :1409  
##  Chicago Cubs        : 1   3rd Qu.:734.0   3rd Qu.:5575   3rd Qu.:1441  
##  Chicago White Sox   : 1   Max.   :875.0   Max.   :5710   Max.   :1600  
##  (Other)             :24                                                
##     homeruns        bat_avg         strikeouts    stolen_bases   
##  Min.   : 91.0   Min.   :0.2330   Min.   : 930   Min.   : 49.00  
##  1st Qu.:118.0   1st Qu.:0.2447   1st Qu.:1085   1st Qu.: 89.75  
##  Median :154.0   Median :0.2530   Median :1140   Median :107.00  
##  Mean   :151.7   Mean   :0.2549   Mean   :1150   Mean   :109.30  
##  3rd Qu.:172.8   3rd Qu.:0.2602   3rd Qu.:1248   3rd Qu.:130.75  
##  Max.   :222.0   Max.   :0.2830   Max.   :1323   Max.   :170.00  
##                                                                  
##       wins          new_onbase        new_slug         new_obs      
##  Min.   : 56.00   Min.   :0.2920   Min.   :0.3480   Min.   :0.6400  
##  1st Qu.: 72.00   1st Qu.:0.3110   1st Qu.:0.3770   1st Qu.:0.6920  
##  Median : 80.00   Median :0.3185   Median :0.3985   Median :0.7160  
##  Mean   : 80.97   Mean   :0.3205   Mean   :0.3988   Mean   :0.7191  
##  3rd Qu.: 90.00   3rd Qu.:0.3282   3rd Qu.:0.4130   3rd Qu.:0.7382  
##  Max.   :102.00   Max.   :0.3490   Max.   :0.4610   Max.   :0.8100  
## 
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

Exercise 1

What type of plot would you use to display the relationship between runs and one of the other numerical variables? A scatter plot is useful for observing the relationship between two numeric variables.

Plot this relationship using the variable at_bats as the predictor. Does the relationship look linear?

#base R scatter plot
plot(mlb11$at_bats,mlb11$runs,xlab="Number of At Bats",
     ylab="Number of Runs",main="Number of Bats vs. Number of Runs MLB 2011 Season")

ggplot(data=mlb11, aes(x=at_bats, y=runs)) +
  geom_point() +
  xlab("Number of At Bats") +
  ylab("Number of Runs") +
  ggtitle("Number of Bats vs. Number of Runs MLB 2011 Season")

Based off the plots, the relationship appears to have a positive linear trend.

If you knew a team’s at_bats, would you be comfortable using a linear model to predict the number of runs? Yes, because it allows one to make a better prediction.

If the relationship looks linear, we can quantify the strength of the relationship with the correlation coefficient.

#cor computes the correlation of x and y if these are vectors. If x and y are matrices then the correlations between the columns of x and the columns of y are computed.
cor(mlb11$runs,mlb11$at_bats)
## [1] 0.610627

In statistics, the correlation coefficient r measures the strength and direction of a linear relationship between two variables on a scatterplot. The value of r is always between +1 and -1. To interpret its value, see which of the following values your correlation r is closest to:

Exactly -1: a perfect downhill (negative) linear relationship

-70: a strong downhill (negative) linear relationship

-50: a moderate downhill (negative) linear relationship

-30: a weak downhill (negative) linear relationship

0: no linear relationship

+30: a weak uphill (positive) linear relationship

+50: a moderate uphill (positive) linear relationship

+70: a strongh uphill (positive) linear relationship

+1: a perfect uphill (positive) linear relationship

If the scatterplot doesn’t indicate there’s at least somewhat of a linear relationship, the correlation doesn’t mean much. Why measure the amount of linear relationship if there isn’t enough of one to speak of? However, you can take the idea of no linear relationship two ways: 1) If no relationship at all exists, calculating the correlation doesn’t make sense because correlation only applies to linear relationships; and 2) If a strong relationship exists but it’s not linear, the correlation may be misleading, because in some cases a strong curved relationship exists. That’s why it’s critical to examine the scatterplot first.

Many folks make the mistake of thinking that a correlation of -1 is a bad thing, indicating no relationship. Just the opposite is true! A correlation of -1 means the data are lined up in a perfect straight line, the strongest negative linear relationship you can get. The “-” (minus) sign just happens to indicate a negative relationship, a downhill line.

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.

Exercise 2

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 two variables apper to be positively correlated (r=0.61) with a slope of approximately 1. The variation appears constant. There are a few outliers, though they appear to follow the general linear trend.

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.

Exercise 3

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?

The smallest sum of squares: 123721.9

The Linear Model

It is rather cumbersome (burdensome; troublesome) 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).

#lm is used to fit linear models. It can be used to carry out regression, single stratum analysis of variance and analysis of covariance 
m1 <- lm(runs ~ at_bats, data = mlb11) #make sure to place y before x

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, R2. The R2 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.

Exercise 4

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?

#marked m1_n for new version
m1_n <- lm(runs ~ homeruns, data = mlb11) 
summary(m1_n)
## 
## 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

\[\hat{y} = 415.2389 + 1.835 * homeruns\]

For this model, 62.7% of the variability in runs is explained by home runs.

Prediction and Prediction Errors

Let’s create a scatterplot with the least squares line laid on top.

plot(mlb11$runs ~ mlb11$at_bats, xlab="Number of At Bats",ylab="Number of Runs",
     main="Number of At Bats vs Number of Runs")
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.

Exercise 5

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? Is this an overestimate or an underestimate, and by how much? In other words, what is the residual for this prediction?

Based on the graph, the line predicts that a team with 5,578 at bats would make 725 runs.

#residuals is a generic function which extracts model residuals from objects returned by modeling functions.
resid(m1)
##           1           2           3           4           5           6 
##   75.960476   63.802426   68.493275  -57.236674   63.040325  -23.837074 
##           7           8           9          10          11          12 
##  176.868025   75.637074   28.473725 -125.575974  -24.378825    5.573124 
##          13          14          15          16          17          18 
##  -55.679025  -14.403674  -19.979225  -15.595525  -26.043175   19.542975 
##          19          20          21          22          23          24 
##  102.031374   27.015475  -51.584925  -58.826475  -18.968626   -3.515676 
##          25          26          27          28          29          30 
##   68.573124  -55.437475  -17.579626  -99.954375  -33.446426  -72.968626

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, xlab = "Number of At Bats",
     ylab = "Residuals",main = "Residuals vs. Number of At Bats") 
abline(h = 0, lty = 3) #adds a horizontal dashed line @ y = 0

Exercise 6

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

There seems to be no pattern in the residuals plot.

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

hist(m1$residuals, xlab="Residuals",main = "Histogram of Residuals", col = "beige")

or a normal probability plot of the residuals.

#qqnorm(y, ylim, main = "Normal Q-Q Plot",xlab = "Theoretical Quantiles", ylab = "Sample Quantiles",plot.it = TRUE, datax = FALSE, ...)
#qqline(y, datax = FALSE, distribution = qnorm,probs = c(0.25, 0.75), qtype = 7, ...)
qqnorm(m1$residuals)
qqline(m1$residuals) #adds diagonal line to the normal prob plot

Exercise 7

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

Yes

Exercise 8

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

On Your Own

Choose another traditional variable from 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?

plot(runs ~ hits, data = mlb11, xlab = "Number of Hits",
     ylab = "Number of Runs", main = "Number of Hits vs. Number of Runs MLB 2011")
m2 <- lm(runs ~ hits, data = mlb11)
abline(m2)

There is linearity between the two variables. Next, we will check the correlation using the cor function.

cor(mlb11$hits,mlb11$runs)
## [1] 0.8012108

How does this relationship compare to the relationship between runs and at_bats? Use the R2 values from the two model summaries to compare. Does your variable seem to predict runs better than at_bats? How can you tell?

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

Since at_bats R-squared/R(cor) (0.3729/0.61) vs hits R-squared/R(cor) (0.6419/.80), hits is a better predictor for runs than at_bats

Now that you can summarize the linear relationship between two variables, investigate the relationships between 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).

preds = c("at_bats","hits","homeruns","bat_avg","strikeouts","stolen_bases","wins")
for (p in preds) {
    R = cor(mlb11[, p], mlb11$runs)
    print(paste(p, ': ', R ^ 2, sep=''))
}
## [1] "at_bats: 0.372865390186806"
## [1] "hits: 0.641938767239419"
## [1] "homeruns: 0.626563569566283"
## [1] "bat_avg: 0.656077134646863"
## [1] "strikeouts: 0.169357932236312"
## [1] "stolen_bases: 0.00291399266657398"
## [1] "wins: 0.360971179446681"
plot(runs ~ bat_avg, data = mlb11,xlab="Batting Average",ylab = "Number of Runs",
     main="Batting Average vs. Number of Runs")
m3 <- lm(runs ~ bat_avg, data = mlb11)
abline(m3)

Now examine the three newer variables. These are the statistics used by the author of Moneyball to predict a teams success. In general, are they more or less effective at predicting runs that the old variables? Explain using appropriate graphical and numerical evidence. Of all ten variables we’ve analyzed, which seems to be the best predictor of runs? Using the limited (or not so limited) information you know about these baseball statistics, does your result make sense?

Check the model diagnostics for the regression model with the variable you decided was the best predictor for runs.

preds = c("new_onbase","new_slug","new_obs")
for (p in preds) {
    R = cor(mlb11[, p], mlb11$runs)
    print(paste(p, ': ', R ^ 2, sep=''))
}
## [1] "new_onbase: 0.849105251446139"
## [1] "new_slug: 0.896870368409638"
## [1] "new_obs: 0.934927126351814"
plot(runs ~ new_obs, data = mlb11,xlab="On Base Plus Slugging",ylab = "Number of Runs",
     main="On Base Plus Slugging vs. Number of Runs")
m4 <- lm(runs ~ new_obs, data = mlb11)
abline(m4)

hist(m4$residuals, xlab="Residuals",main = "Histogram of Residuals", col = "beige")

qqnorm(m4$residuals)
qqline(m4$residuals)