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 you’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.
load(url('http://s3.amazonaws.com/assets.datacamp.com/course/dasi/mlb11.RData'))
In addition to runs scored, there are seven traditionally used variables in the mlb11 data set: at_bats, hits, homeruns, bat_avg (batting average), strikeouts, stolen_bases, and wins. Even though it’s not necessary for this lab, you can always take a refresher on the rules of baseball and a description of the statistics.
There are also three newer variables: new_onbase (on base percentage), new_slug (slugging percentage), and new_obs (on-base plus slugging). For the first portion of the analysis you’ll consider the seven traditional variables. At the end of the lab, you’ll work with the newer variables on your own.
What type of plot would you use to display the relationship between runs and one of the other numerical variables?
scatterplot
Using the correct type of plot of the previous exercises, plot the relationship between runs and at bats, using at bats as the explanatory variable.
There appears to be a linear relationship between the two variables.
plot(mlb11$runs ~ mlb11$at_bats)
TRUE
As you know, when a relationship looks linear you can quantify the strength of the relationship with the correlation coefficient. R has a very usefull function to calculate the correlation: cor(input1, input2)
# Calculate the correlation between runs and at_bats:
correlation = cor(mlb11$runs, mlb11$at_bats)
# Print the result:
correlation
## [1] 0.6106
The correlation coefficient shows a positive linear correlation. Let’s now see if you can use this insight to construct a linear model for these variables.
Think back to the way that you described the distribution of a single variable. Recall that you 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.
Looking at the plot, which of the following best describe the relationship between these two variables?
The relationship is positive, linear, and moderately strong. There is one clear outlier, a team with 5520 at bats.
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 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, x1, y1, x2, y2)
This function will first draw a scatterplot of the first two arguments \(x\) and \(y\). Then it draws two points \((x_1, y_1)\) and \((x_2, y_2)\) that are shown as red circles. These points are used to draw the line that represents the regression estimate. The line you specified is 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_ss command and add the argument showSquares = TRUE.
plot_ss(x = mlb11$at_bats, y = mlb11$runs, x1, y1, x2, y2, showSquares = TRUE)
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(mlb11$runs ~ mlb11$at_bats)
abline(lm(mlb11$runs ~ mlb11$at_bats))
# Use the 'plot_ss' function to draw an estimated regression line. Two
# points are given to get you started:
x1 = 5400
y1 = 750
x2 = 5700
y2 = 650
plot_ss(x = mlb11$at_bats, y = mlb11$runs, x1, y1, x2, y2, showSquares = TRUE)
##
## Call:
## lm(formula = y ~ x, data = pts)
##
## Coefficients:
## (Intercept) x
## 2550.000 -0.333
##
## Sum of Squares: 302572
Removing the coordinates for estimating and adding leastSquares = TRUE to the function gives us the best fitting line.
plot_ss(x = mlb11$at_bats, y = mlb11$runs, showSquares = TRUE, leastSquares=T)
##
## Call:
## lm(formula = y ~ x)
##
## Coefficients:
## (Intercept) x
## -2789.243 0.631
##
## Sum of Squares: 123722
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).
model = lm(formula, data = your_dataframe)
The first argument in the function lm is a formula that takes the form y ~ x. Here it can be read that you want to make a linear model of y as a function of x. The second argument specifies that R should look in the my_dataframe data frame to find the x and y variables.
# Use the 'lm' function to make the linear model:
m1 = lm(runs ~ at_bats, data=mlb11)
# Print the model:
m1
##
## Call:
## lm(formula = runs ~ at_bats, data = mlb11)
##
## Coefficients:
## (Intercept) at_bats
## -2789.243 0.631
lmThe output of lm is an object that contains all of the information you need about the linear model that was just fit. You can access this information using the summary function.
m1 = lm(runs ~ at_bats, data = mlb11)
# The summary of 'm1':
summary(m1)
##
## Call:
## lm(formula = runs ~ at_bats, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -125.6 -47.0 -16.6 54.4 176.9
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -2789.243 853.696 -3.27 0.00287 **
## at_bats 0.631 0.155 4.08 0.00034 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 66.5 on 28 degrees of freedom
## Multiple R-squared: 0.373, Adjusted R-squared: 0.35
## F-statistic: 16.6 on 1 and 28 DF, p-value: 0.000339
In this exercise, you should first make the assignment described in the instructions below. After that, read the rest of this description.
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} = 415.2389 + 1.8345 \cdot \text{homeruns} = 415.2\)
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, 62.7% of the variability in runs is explained by homeruns.
# Use the 'lm' function to make the linear model. Print the summary:
m2 = lm(runs ~ homeruns, data=mlb11)
summary(m2)
##
## Call:
## lm(formula = runs ~ homeruns, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -91.61 -33.41 3.23 24.29 104.63
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 415.239 41.678 9.96 1.0e-10 ***
## homeruns 1.835 0.268 6.85 1.9e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 51.3 on 28 degrees of freedom
## Multiple R-squared: 0.627, Adjusted R-squared: 0.613
## F-statistic: 47 on 1 and 28 DF, p-value: 1.9e-07
Refit the model that uses homeruns to predict runs.
summary(lm(runs ~ homeruns, data = mlb11))
##
## Call:
## lm(formula = runs ~ homeruns, data = mlb11)
##
## Residuals:
## Min 1Q Median 3Q Max
## -91.61 -33.41 3.23 24.29 104.63
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 415.239 41.678 9.96 1.0e-10 ***
## homeruns 1.835 0.268 6.85 1.9e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 51.3 on 28 degrees of freedom
## Multiple R-squared: 0.627, Adjusted R-squared: 0.613
## F-statistic: 47 on 1 and 28 DF, p-value: 1.9e-07
What does the slope tell us in the context of the relationship between success of a team and its home runs?
For each additional home run, the model predicts 1.83 more runs, on average.
The function abline plots a line based on its slope and intercept. 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.
Tip: abline takes the slope and intercept as arguments. Here, we use a shortcut by providing the model itself, which contains both parameter estimates: abline(m1)
m1 = lm(runs ~ at_bats, data = mlb11)
# Plot the least squares line:
plot(runs ~ at_bats, data=mlb11)
abline(m1)
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,579 at-bats? Use the console to see if this is an overestimate or an underestimate, and by how much? The data mlb11 and linear model m1 are already loaded.
What is the residual for the prediction of runs for a team with 5,579 at-bats?
-15.32
To assess whether the linear model is reliable, you need to check for three things:
1. linearity
2. nearly normal residuals
3. constant variability.
You already checked if the relationship between runs and at-bats is linear using a scatterplot. You should also verify this condition with a plot of the residuals vs. at-bats. The lty=3 argument adds a horizontal dashed line at y = 0: plot(m1$residuals ~ mlb11$at_bats) abline(h = 0, lty = 3).
Which of the following statements about the residual plot is false?
The residuals show a curved pattern.
Point 2, nearly normal residuals: To check this condition, a normal probability plot of the residuals (the graph is shown).
qqnorm(m1$residuals)
qqline(m1$residuals)
The final code statement here adds a diagonal line to the normal probability plot.
You can also look at a histogram via hist(m1$residuals).
Based on the histogram and the normal probability plot, the nearly normal residuals condition appears to be met?
TRUE
Based on the plot, the constant variability condition (point 3) appears to be met.
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?
batting average
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?
on-base plus slugging (new obs)