---
title: "Worksheet 4"
output:
  pdf_document: default
  html_notebook: default
---



## Author: Enter name of the author here

## Discussants: Enter the names of other people who you discussed this problem set with




$\\$




The purposes of these exericses is to gain experiment examing correlation values and building linear regression models. Some function that will be useful for completing these exercises include: dim(), max(), plot(), cor(), coef() and predict().  The worksheet is due at 11:59pm on Sunday March 5th. Be sure to include all code you used to get your answers in the pdf that you turn in.


<!-- This R chunk sets some parameters that will be used in the rest of the document. -->
```{r message=FALSE, warning=FALSE, tidy=TRUE, echo = FALSE}
    library(knitr)
    # makes sure the code is wrapped to fit when it creats a pdf
    opts_chunk$set(tidy.opts=list(width.cutoff=60)) 
    set.seed(1)  # set the random number generator to always give the same sequence of random numbers
```




$\\$




**Exercise 1:** To complete the following exercises we will need the statistics for each baseball team for each season. Let's start by loading a data frame that has team batting statistics from every team that has played 162 games. This data is stored in a variable called team.batting.162 and can be loaded using the using the code below. Once you have loaded it report how many variables there are in this data frame using the dim() function. 

```{r message=FALSE, warning=FALSE, tidy=TRUE}

  load('/home/shared/baseball_stats_2017/team_batting_stats.Rda')


  
```

**Answers:**   






$\\$







**Exercise 2:** In class we saw that on-base plus slugging (OPS) had the highest correlation with runs scored of all the statistics we tested. However it is possible that other statistics might exist that work better that OPS. One such statistic is called "batter's run average" (BRA) which is on-base percentage *times* slugging percentage, i.e., BRA = OBP * SlugPct (this is different than OPS which is OBP + SlugPct). In the following exercises we will test if BRA is a "better"" statistic than OPS. 

We can add a new variable to a data frame with the syntax: my.data.frame$new.variable.name <- new.variable. Below is code that adds BRA to the data frame. What is the maximum BRA that any team has? Is this higher or lower than the maximum team slugging percentage?     
```{r message=FALSE, warning=FALSE}

  team.batting.162$BRA <- team.batting.162$OBP * team.batting.162$SlugPct 
  
   

```

**Answers:** 






$\\$








**Exercise 3:** As we've seen previously, we can create a scatter plot between two vectors x and y using the plot(x, y) function. We can also calculate the correlation between two vectors using the cor(x, y). Create a scatter plot of BRA and Runs (R) and put the correlation value between BRA and Runs in the title of the plot (remember we can use plot(x, y, main = 'my title' to set the title of a plot). Is the correlation of BRA and Runs higher than the correlation between OPS and runs? Which statistic do you think would be best to use when judging a player's ability?   
```{r message=FALSE, warning=FALSE, tidy=TRUE}


```

**Answers:** 







$\\$







**Exercise 4:** We also discussed in class that we can create a linear regression model in R using the lm() function as:
fit <- lm(response.variable ~ explanatory.variable). This function returns an R object (which we stored in the variable *fit*) that has information about the regression model that was created. We can extract the coefficients of the linear regression model using the coef() function - i.e, we can extract the intercept *a* and slope *b* in the equation $\hat{y} = a + b \cdot x$ using coef(fit). 

Use the lm() function to calculate the slope and the offset for a linear equation that predictions the number runs a team will score in a season as a function of the team's BRA, and save the output of this linear model to an object called *bra.fit*. What are the slope and offset values found by this linear regression? Write down the linear equation for predicting the number of runs a team would score as a function of BRA using these linear model coefficients. Then report the predicted number of runs a team would score if they had a BRA of 0. Also, report how many more runs a team would be predicted to score in a season if a team increases their BRA by .01. 
```{r message=FALSE, warning=FALSE, tidy=TRUE}




```

**Answers:** 







$\\$






**Exercise 5:** In the analysis above we saved the output of the lm() function to an object called *bra.fit*. Below, create a  scatter plot between BRA and runs, and then run the command: abline(bra.fit, col = "red"). What happens when you run the abline() function?    
```{r message=FALSE, warning=FALSE, tidy=TRUE}


```
**Answers:** 
  

  
 
  
  
$\\$






**Exercise 6:** The function predict(fit) will return a vector that has predicted values for each value of the explanatory variables that went into your linear model - i.e., the predict() function returns $\hat{y}_i$ for each $x_i$ that was used to create the linear model. As we went over in class, you can take this vector of predicted $\hat{y}$ values and calculate the residuals by subtracting the actual values $y$ from these predicted values. In the case of predicting runs scored from BRA, the $y_i$ correspond to the number of runs that the $i^{th}$ team scored in a season, the $x_i$ correspond to the $i^{th}$ team's BRA, and the $\hat{y}_i$ correspond to the number of runs predicted by the linear model for the $i^{th}$ team.

Below calculate the vector of residuals from predicting runs as a function of BRA, and store the resulting residuals in a vector called *residuals*. Also report what the maximum and minimum residuals are.

```{r message=FALSE, warning=FALSE, tidy=TRUE}




```

**Answers:** 





$\\$







**Exercise 7:**  We can also calculate the *root mean squared error* (RMSE) by squaring these residules, taking the mean of the squared values, and taking the square root. Apply these operations and calculate the RMSE for the predicted runs using BRA (Note: it might be helpful to create intermediate variables in this process), and report the RMSE value that you get. Also describe about how many runs are the predictions made using this linear model off by. Finally, create a linear model that uses OPS to predict runs, and calculate the RMSE for predicted runs from OPS. How many runs is this OPS model typically off by? Based on these RMSE values, does BRA or OPS appear to be better at predicted the number of runs a team will score?     

```{r message=FALSE, warning=FALSE, tidy=TRUE}





```

**Answers:** 
















