Define two new variables in the Teams data frame in the Lahman package. a. batting average (BABA). Batting average is the ratio of hits (H) to at-bats (AB). b. slugging percentage (SLGSLG). Slugging percentage is total bases divided by at-bats. To compute total bases, you get 1 for a single, 2 for a double, 3 for a triple, and 4 for a home run. c. Plot out the SLGSLG versus yearID, showing the individual teams and a smooth curve. d. Same as (c), but plot BABA versus year.
时间: 2024-01-29 15:04:27 浏览: 34
To define the two new variables, we can use the following code:
```{r}
library(Lahman)
# Compute batting average
Teams$BABA <- Teams$H / Teams$AB
# Compute slugging percentage
Teams$SLGSLG <- (Teams$H - Teams$X2B - Teams$X3B - Teams$HR) + 2 * Teams$X2B + 3 * Teams$X3B + 4 * Teams$HR
Teams$SLGSLG <- Teams$SLGSLG / Teams$AB
# Plot SLGSLG versus yearID
library(ggplot2)
ggplot(Teams, aes(x = yearID, y = SLGSLG, color = teamID)) +
geom_point() +
geom_smooth()
# Plot BABA versus yearID
ggplot(Teams, aes(x = yearID, y = BABA, color = teamID)) +
geom_point() +
geom_smooth()
```
In the code above, we first compute the batting average and slugging percentage for each team using the formulae provided. We then use ggplot2 to create two plots, one showing SLGSLG versus yearID and the other showing BABA versus yearID. In both plots, we use different colors to represent different teams. The `geom_smooth()` function adds a smooth curve to the plot.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)