load("more/mlb11.RData")

##Ex1: 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?
##We would use a scatterplot
plot(mlb11$at_bats, mlb11$runs)

##There seems to be a positive linear relationship between the two variables.
##However, the association seems to be weak and I would not be comfortable using a linear model.

cor(mlb11$runs, mlb11$at_bats)
## [1] 0.610627
##Ex2: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 relationship between the two variables is linear and positive, but the association seems to be weak as it is not a close fit. 
##The data seems to have outliers.  

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
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
##Ex3: 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?

##Run 01
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
##Call:  lm(formula = y ~ x, data = pts)
##Coefficients:
##  (Intercept)            x  
##-4512.3812       0.9459  
##Sum of Squares:  152900.3

##Run 02
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
##Call:  lm(formula = y ~ x, data = pts)
##Coefficients:
##  (Intercept)            x  
##-2177.5958       0.5191  
##Sum of Squares:  126509.1

##Run 03
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
##Call:  lm(formula = y ~ x, data = pts)
##Coefficients:
##  (Intercept)            x  
##-2771.788        0.625  
##Sum of Squares:  128955.2  

##Smallest sum of squares is 126509.1

#THE LINEAR model

m1 <- lm(runs ~ at_bats, data = mlb11)
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
##EX4: 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?
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
##The equation is Runs= 415.24 + 1.83 * homeruns

#Prediction and prediction errors 

plot(mlb11$runs ~ mlb11$at_bats)
abline(m1)

##Ex5: 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?
m1 <- lm(runs ~ at_bats, data = mlb11)  
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
-2789.24 + .6305*5578
## [1] 727.689
##He would predict 727 Runs
plot(mlb11$runs ~ mlb11$at_bats)
abline(m1)

##This is an overestimate as we can see from the plot that the actual number of runs is close to 700.


#Model Diagnostics
plot(m1$residuals ~ mlb11$at_bats)
abline(h = 0, lty = 3)

##Ex6: Is there any apparent pattern in the residuals plot? What does this indicate about the linearity of the relationship between runs and at-bats?
##The residuals seem to be nearly normal and we can check as follows.

hist(m1$residuals)

qqnorm(m1$residuals)
qqline(m1$residuals)

##There are similar no of points both above and below the qqplot and so the relationship seems to be linear.

##Ex7: Based on the histogram and the normal probability plot, does the nearly normal residuals condition appear to be met?
##It is reasonable to conclude that the condition is met. 

##Ex8: Based on the plot in (1), does the constant variability condition appear to be met?
##The variability of points around the least squares lines seems to be close and so the condition appears to have been met. 

#ON YOUR OWN

##1. 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?
##I have chosen no of hits as the independent variable.   
plot(mlb11$hits,mlb11$runs)

##The relation between the two varaibles seems to be positive and linear. 
m3<- lm(runs ~ hits, data=mlb11)

##2.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(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
##R square for regression with hits and runs is 64%.
##This is much higher than m1 at 37%, so the model m3 fits the data better.

##3. 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).
par(mfrow=c(3,2))
plot(mlb11$at_bats,mlb11$runs)
plot(mlb11$hits,mlb11$runs)
plot(mlb11$homeruns,mlb11$runs)
plot(mlb11$strikeouts,mlb11$runs)
plot(mlb11$stolen_bases,mlb11$runs)

m4<- lm(runs ~ strikeouts, data=mlb11)
m5<- lm(runs ~ stolen_bases, data=mlb11)

##RSquare for

##m1 is 37%
##m2 is 63%
##m3 is 64%
##m4 is 17%
##m5 is .3%

##The variables hits and homeruns have the strongest linear relationship with runs.
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
##4. 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?
par(mfrow=c(3,2))

plot(mlb11$bat_avg,mlb11$runs)
plot(mlb11$wins,mlb11$runs)
plot(mlb11$new_onbase,mlb11$runs)
plot(mlb11$new_slug,mlb11$runs)
plot(mlb11$new_obs,mlb11$runs)
m6<- lm(runs ~ bat_avg, data=mlb11)
m7<- lm(runs ~ wins, data=mlb11)
m8<- lm(runs ~ new_onbase, data=mlb11)
m9<- lm(runs ~ new_slug, data=mlb11)
m10<- lm(runs ~ new_obs, data=mlb11)

##RSquare for
##m6 is 66%
##m7 is 36%
##m8 is 85%
##m9 is 90%
##m10 is 93%

##The new variables are more effective at predicting runs than the old variables.
##The best predictor is m10 at 93% Rsquare.
##It doesn't make sense to me how on base plus slogging has the highest linear relationship with runs.

##5. Check the model diagnostics for the regression model with the variable you decided was the best predictor for runs.
plot(m10)

par(mfrow=c(1,2))

hist(m10$residuals)
qqnorm(m10$residuals)
qqline(m10$residuals)

##The points are very close to the straight line and confirms normality of the residual data.
plot(m10$residuals)
##The scatterplot seems to indicate the condition of constant variability is met.