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.

library(psych)
library(corrr)
## Warning: package 'corrr' was built under R version 3.5.3
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.

  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? If you knew a team’s at_bats, would you be comfortable using a linear model to predict the number of runs?

Answer:

I will use scatterplot to show how each datapoints are distributed on the X = at_bats and y= runs. Based on data data cluster it looks like data is very spread , I will not be very comfortable using a linear model to predict the number of runs.

plot( mlb11$at_bats,mlb11$runs)

mlb11[,c(2,3)]
##    runs at_bats
## 1   855    5659
## 2   875    5710
## 3   787    5563
## 4   730    5672
## 5   762    5532
## 6   718    5600
## 7   867    5518
## 8   721    5447
## 9   735    5544
## 10  615    5598
## 11  708    5585
## 12  644    5436
## 13  654    5549
## 14  735    5612
## 15  667    5513
## 16  713    5579
## 17  654    5502
## 18  704    5509
## 19  731    5421
## 20  743    5559
## 21  619    5487
## 22  625    5508
## 23  610    5421
## 24  645    5452
## 25  707    5436
## 26  641    5528
## 27  624    5441
## 28  570    5486
## 29  593    5417
## 30  556    5421
pairs.panels(mlb11[,c(2,3)])

cor.plot(mlb11[,c(2,3)],numbers=TRUE)

cor.test(mlb11$at_bats,mlb11$runs)
## 
##  Pearson's product-moment correlation
## 
## data:  mlb11$at_bats and mlb11$runs
## t = 4.0801, df = 28, p-value = 0.0003388
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.3209675 0.7958231
## sample estimates:
##      cor 
## 0.610627
  densityBy(mlb11,c("runs"))

  densityBy(mlb11,c("at_bats"))

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
#Psych pacakge TEst 
corr.test(x = mlb11$at_bats, y = mlb11$runs)
## Call:corr.test(x = mlb11$at_bats, y = mlb11$runs)
## Correlation matrix 
## [1] 0.61
## Sample Size 
## [1] 30
## Probability values  adjusted for multiple tests. 
## [1] 0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option
cor.plot(mlb11[,c(2,3)])

R <- corr.test(mlb11[,c(2,3)])
print(R, short=F)
## Call:corr.test(x = mlb11[, c(2, 3)])
## Correlation matrix 
##         runs at_bats
## runs    1.00    0.61
## at_bats 0.61    1.00
## Sample Size 
## [1] 30
## Probability values (Entries above the diagonal are adjusted for multiple tests.) 
##         runs at_bats
## runs       0       0
## at_bats    0       0
## 
##  Confidence intervals based upon normal theory.  To get bootstrapped values, try cor.ci
##            raw.lower raw.r raw.upper raw.p lower.adj upper.adj
## runs-at_bt      0.32  0.61       0.8     0      0.32       0.8
cor.ci(mlb11[,c(2,3)])

## Call:corCi(x = x, keys = keys, n.iter = n.iter, p = p, overlap = overlap, 
##     poly = poly, method = method, plot = plot, minlength = minlength)
## 
##  Coefficients and bootstrapped confidence intervals 
##         runs at_bt
## runs    1.00      
## at_bats 0.61 1.00 
## 
##  scale correlations and bootstrapped confidence intervals 
##            lower.emp lower.norm estimate upper.norm upper.emp p
## runs-at_bt      0.24       0.31     0.61       0.79      0.77 0

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. ### Answer We can tell the moderate strong relationship of these two variables by looking at the calculated correlation coefficient of 0.610627. But we see that correlation coefficient 0.610627 turns out to be far below from +1 making it moderately strong.

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
# 
# lm(formula = runs ~ at_bats, data = mlb11[,c(2,3)])
# 
# pairs.panels(mlb11[,c(2,3)],stars = TRUE)
# 
# pairs.panels(mlb11[,c(2,3)],stars = TRUE,lm = TRUE)

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?

Answer

my smallest Sum of Squares: 128210.2 , I noticed regression line tends to lean towrds where we have more clouds of datapoints.

# Run1 <- plot_ss(x = mlb11$at_bats, y = mlb11$runs, showSquares = TRUE)
#                                 
# Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#  -4569.1329       0.9554  
# 
# Sum of Squares:  149551.7
# --------------------------------------------------------------------
# lmd <- plot_ss(x = mlb11$at_bats, y = mlb11$runs, showSquares = TRUE)
#                                 
# Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#    -5197.81         1.07  
# 
# Sum of Squares:  168545.5
#------------------------------------------------------------------------
# Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#   -2049.683        0.494  
# 
# Sum of Squares:  133399.6
#-------------------------------------------------------------------------
#Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#  -1645.3134       0.4241  
# 
# Sum of Squares:  131992.8
#-------------------------------------------------------------------------
# Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#   -1757.847        0.442  
# 
# Sum of Squares:  133372.8
#-------------------------------------------------------------------------
# Call:
# lm(formula = y ~ x, data = pts)
# 
# Coefficients:
# (Intercept)            x  
#  -3494.0654       0.7594  
# 
# Sum of Squares:  128210.2
#-------------------------------------------------------------------------
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

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?

Answer

yhat <- bo + b1 * X yhat = 415.239 b1 = ((X-Xmean)(Y-Ymean) )/ (X-Xmean)^2 = 1.8345 Correlation Coefficient : 0.79

By looking at the plot we can say that the relationship between runs and home runs is linear positive and relatively strong as the correlation coefficient 0.7916 is closer to +1

mlb11[,c(2,5)]
##    runs homeruns
## 1   855      210
## 2   875      203
## 3   787      169
## 4   730      129
## 5   762      162
## 6   718      108
## 7   867      222
## 8   721      185
## 9   735      163
## 10  615       95
## 11  708      191
## 12  644      117
## 13  654      148
## 14  735      183
## 15  667      155
## 16  713      153
## 17  654      154
## 18  704      154
## 19  731      172
## 20  743      186
## 21  619      103
## 22  625      149
## 23  610      107
## 24  645      114
## 25  707      172
## 26  641      173
## 27  624      154
## 28  570      121
## 29  593       91
## 30  556      109
plot( mlb11$homeruns , mlb11$runs)

pairs.panels(mlb11[,c(2,5)])

cor.plot(mlb11[,c(2,5)],numbers=TRUE)

corr.test(mlb11$homeruns , mlb11$runs)
## Call:corr.test(x = mlb11$homeruns, y = mlb11$runs)
## Correlation matrix 
## [1] 0.79
## Sample Size 
## [1] 30
## Probability values  adjusted for multiple tests. 
## [1] 0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option
corrr::correlate(mlb11[,2:5]) 
## 
## Correlation method: 'pearson'
## Missing treated using: 'pairwise.complete.obs'
## # A tibble: 4 x 5
##   rowname    runs at_bats   hits homeruns
##   <chr>     <dbl>   <dbl>  <dbl>    <dbl>
## 1 runs     NA       0.611  0.801    0.792
## 2 at_bats   0.611  NA      0.846    0.377
## 3 hits      0.801   0.846 NA        0.471
## 4 homeruns  0.792   0.377  0.471   NA
  corrr::network_plot(correlate(mlb11[,2:5]))
## 
## Correlation method: 'pearson'
## Missing treated using: 'pairwise.complete.obs'

  plot_ss(x = mlb11$homeruns, y = mlb11$runs, showSquares = TRUE)

## Click two points to make a line.
                                
## Call:
## lm(formula = y ~ x, data = pts)
## 
## Coefficients:
## (Intercept)            x  
##     415.239        1.835  
## 
## Sum of Squares:  73671.99
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
# 
#   densityBy(mlb11,c("runs"))
#   densityBy(mlb11,c("homeruns"))

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)

# plot_ss(x = mlb11$at_bats, y = mlb11$runs, showSquares = TRUE)
# summary(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? Is this an overestimate or an underestimate, and by how much? In other words, what is the residual for this prediction?
b0 <- -2789.242885
b1 <- 0.630549993
x <- 5578
Yhat <- b0 + b1*x
Yhat
## [1] 727.965
mlb11[order(mlb11$runs,mlb11$at_bats),1:3]
##                     team runs at_bats
## 30      Seattle Mariners  556    5421
## 28  San Francisco Giants  570    5486
## 29      San Diego Padres  593    5417
## 23    Pittsburgh Pirates  610    5421
## 10        Houston Astros  615    5598
## 21       Minnesota Twins  619    5487
## 27  Washington Nationals  624    5441
## 22       Florida Marlins  625    5508
## 26        Atlanta Braves  641    5528
## 12   Los Angeles Dodgers  644    5436
## 24     Oakland Athletics  645    5452
## 17     Chicago White Sox  654    5502
## 13          Chicago Cubs  654    5549
## 15    Los Angeles Angels  667    5513
## 18     Cleveland Indians  704    5509
## 25        Tampa Bay Rays  707    5436
## 11     Baltimore Orioles  708    5585
## 16 Philadelphia Phillies  713    5579
## 6          New York Mets  718    5600
## 8      Milwaukee Brewers  721    5447
## 4     Kansas City Royals  730    5672
## 19  Arizona Diamondbacks  731    5421
## 9       Colorado Rockies  735    5544
## 14       Cincinnati Reds  735    5612
## 20     Toronto Blue Jays  743    5559
## 5    St. Louis Cardinals  762    5532
## 3         Detroit Tigers  787    5563
## 1          Texas Rangers  855    5659
## 7       New York Yankees  867    5518
## 2         Boston Red Sox  875    5710
mlb11[which(mlb11$at_bats >= 5578),1:3]
##                     team runs at_bats
## 1          Texas Rangers  855    5659
## 2         Boston Red Sox  875    5710
## 4     Kansas City Royals  730    5672
## 6          New York Mets  718    5600
## 10        Houston Astros  615    5598
## 11     Baltimore Orioles  708    5585
## 14       Cincinnati Reds  735    5612
## 16 Philadelphia Phillies  713    5579

We see with 5579 bats Phili team made 713 runs, lets how much our model would estimate for this bat.Be checking below its clear model is overestimating it in this case.

b0 <- -2789.242885
b1 <- 0.630549993
x <- 5579
Yhat <- b0 + b1*x
Yhat
## [1] 728.5955
actaul_score <- 713 
error <- actaul_score - Yhat  # residual 

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.

Residual = Observed value - Predicted value e = y - y

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?

Answer

Based on the plot we can clearly say that there is no apparent pattern in the distribution as the numbers appear to be scattered unevenly around the dashed line and appear to be skewed. But it can be considered as a linear relationship.

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

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

Answer

Looking at the histogram and the plot I would say that the nearly normal residuals condition has been met.

Constant variability:

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

Answer

The variation of points around the least squares line appear to be reasonably constant thus an inference can be made that the constant variability condition has been met. * * *

On Your Own

Answer

From the pairs.panels we can see from the 1st 8 varaible there are few with high Correlation . I am choosing at_bat and hits with .85 correlation.

From the plot and summary statistics below it looks to me that the two variables fit a liner model. Even R-squared of 0.7165, is good indicator of better fit of this regression line.

pairs.panels(mlb11[,1:8])

corr.test(x = mlb11$at_bats, y= mlb11$hits)
## Call:corr.test(x = mlb11$at_bats, y = mlb11$hits)
## Correlation matrix 
## [1] 0.85
## Sample Size 
## [1] 30
## Probability values  adjusted for multiple tests. 
## [1] 0
## 
##  To see confidence intervals of the correlations, print with the short=FALSE option
cor(x = mlb11$at_bats, y= mlb11$hits)
## [1] 0.846472
m3 <- lm(hits ~ at_bats, data = mlb11)
plot(mlb11$hits ~ mlb11$at_bats, main = "Relationship3")
abline(m3)

hist(m3$residuals)

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

summary(m3)
## 
## Call:
## lm(formula = hits ~ at_bats, data = mlb11)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -68.053 -34.654  -7.322  17.752  96.256 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -3688.5706   605.9993  -6.087 1.45e-06 ***
## at_bats         0.9229     0.1097   8.413 3.77e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 47.19 on 28 degrees of freedom
## Multiple R-squared:  0.7165, Adjusted R-squared:  0.7064 
## F-statistic: 70.77 on 1 and 28 DF,  p-value: 3.773e-09

  • How does this relationship compare to the relationship between 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?

Answer

R-squared ranges between 0 and 1, 1 being best possble fit and 0 being the worst fit indicator of regression line.

From the two R-square Correlation between hits and at_bats is high with R-squired = 0.70 , where as the same value for runs and at_bats is .35 .

Lower the R^2 means bigger the Sum of Squired of Erros , implies we are adding more erros / ressidue in our predictions.

New varaible predicts better with 70% exaplined varaibility in the model .

summary(m3)
## 
## Call:
## lm(formula = hits ~ at_bats, data = mlb11)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -68.053 -34.654  -7.322  17.752  96.256 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -3688.5706   605.9993  -6.087 1.45e-06 ***
## at_bats         0.9229     0.1097   8.413 3.77e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 47.19 on 28 degrees of freedom
## Multiple R-squared:  0.7165, Adjusted R-squared:  0.7064 
## F-statistic: 70.77 on 1 and 28 DF,  p-value: 3.773e-09
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

  • 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).

Answer

From below graph with correlation we can say that runs is better predicated with bat_avg , with Correlation of 0.81 .

pairs.panels(mlb11[,2:8])

m3 <- lm(runs ~ bat_avg, data = mlb11)
hist(m3$residuals)

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


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

Answer

based on cor.plot(mlb11[,2:12],numbers=TRUE) we can say that “new_onbase” “new_slug” “new_obs” are the best predictor for run with mnew_obs being very fit with high correlation of .97 with runs , it also shows Rsuared closed to 0.9349 ~ 1.

names(mlb11)
##  [1] "team"         "runs"         "at_bats"      "hits"        
##  [5] "homeruns"     "bat_avg"      "strikeouts"   "stolen_bases"
##  [9] "wins"         "new_onbase"   "new_slug"     "new_obs"
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
corrr::correlate(mlb11[,2:12])
## 
## Correlation method: 'pearson'
## Missing treated using: 'pairwise.complete.obs'
## # A tibble: 11 x 12
##    rowname     runs  at_bats    hits homeruns bat_avg strikeouts
##    <chr>      <dbl>    <dbl>   <dbl>    <dbl>   <dbl>      <dbl>
##  1 runs     NA        0.611    0.801    0.792   0.810    -0.412 
##  2 at_bats   0.611   NA        0.846    0.377   0.755    -0.463 
##  3 hits      0.801    0.846   NA        0.471   0.988    -0.617 
##  4 homeru~   0.792    0.377    0.471   NA       0.472    -0.171 
##  5 bat_avg   0.810    0.755    0.988    0.472  NA        -0.635 
##  6 strike~  -0.412   -0.463   -0.617   -0.171  -0.635    NA     
##  7 stolen~   0.0540  -0.108   -0.126   -0.117  -0.123     0.0876
##  8 wins      0.601    0.0622   0.298    0.661   0.351    -0.281 
##  9 new_on~   0.921    0.598    0.855    0.616   0.882    -0.487 
## 10 new_sl~   0.947    0.620    0.818    0.863   0.828    -0.410 
## 11 new_obs   0.967    0.628    0.851    0.811   0.867    -0.444 
## # ... with 5 more variables: stolen_bases <dbl>, wins <dbl>,
## #   new_onbase <dbl>, new_slug <dbl>, new_obs <dbl>
corrr::as_matrix(correlate(mlb11[,2:12]))
## 
## Correlation method: 'pearson'
## Missing treated using: 'pairwise.complete.obs'
##                     runs     at_bats       hits   homeruns    bat_avg
## runs                  NA  0.61062705  0.8012108  0.7915577  0.8099859
## at_bats       0.61062705          NA  0.8464720  0.3765152  0.7553744
## hits          0.80121081  0.84647201         NA  0.4708379  0.9879576
## homeruns      0.79155769  0.37651521  0.4708379         NA  0.4715115
## bat_avg       0.80998589  0.75537437  0.9879576  0.4715115         NA
## strikeouts   -0.41153120 -0.46342423 -0.6172284 -0.1707547 -0.6348140
## stolen_bases  0.05398141 -0.10752931 -0.1263302 -0.1173235 -0.1231475
## wins          0.60080877  0.06215611  0.2976591  0.6606140  0.3507933
## new_onbase    0.92146907  0.59814536  0.8548459  0.6163270  0.8823015
## new_slug      0.94703240  0.62027677  0.8182380  0.8628315  0.8284896
## new_obs       0.96691630  0.62790901  0.8508329  0.8106669  0.8670994
##              strikeouts stolen_bases        wins  new_onbase    new_slug
## runs         -0.4115312   0.05398141  0.60080877  0.92146907  0.94703240
## at_bats      -0.4634242  -0.10752931  0.06215611  0.59814536  0.62027677
## hits         -0.6172284  -0.12633021  0.29765911  0.85484588  0.81823795
## homeruns     -0.1707547  -0.11732353  0.66061399  0.61632698  0.86283152
## bat_avg      -0.6348140  -0.12314745  0.35079332  0.88230150  0.82848956
## strikeouts           NA   0.08764160 -0.28072689 -0.48688025 -0.40982184
## stolen_bases  0.0876416           NA -0.06459410 -0.03325633 -0.07412811
## wins         -0.2807269  -0.06459410          NA  0.55227777  0.61416591
## new_onbase   -0.4868803  -0.03325633  0.55227777          NA  0.87186451
## new_slug     -0.4098218  -0.07412811  0.61416591  0.87186451          NA
## new_obs      -0.4439747  -0.06184629  0.61207502  0.93728337  0.98776446
##                  new_obs
## runs          0.96691630
## at_bats       0.62790901
## hits          0.85083295
## homeruns      0.81066685
## bat_avg       0.86709944
## strikeouts   -0.44397466
## stolen_bases -0.06184629
## wins          0.61207502
## new_onbase    0.93728337
## new_slug      0.98776446
## new_obs               NA
 cor.plot(mlb11[,2:12],numbers=TRUE)

 mnew_obs <- lm(runs ~ new_obs, data = mlb11)
mnew_slug <- lm(runs ~ new_slug, data = mlb11)
mnew_onbase <- lm(runs ~ new_onbase, data = mlb11)
summary(mnew_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
summary(mnew_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
summary(mnew_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
mnew_obs <- lm(runs ~ new_obs, data = mlb11)
hist(mnew_obs$residuals)

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


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

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.