Calculate a closing average
Now that you've explored some trends in your Red Sox data, you want to produce some useful indicators. In this exercise, you'll calculate the team's win/loss average at the end of each season. In financial terms, you can think of this as the team's value at the close of the season.
To calculate a closing win/loss average, you'll need to combine a few of the commands used in previous chapters.
First, you'll identify wins based on the score of each game. You can do this using a simple ifelse() command and the knowledge that the Red Sox win each game in which they score more points than the opposing team.
Second, you'll identify the date of the last game in each season using endpoints(). This command identifies the last date in your object within certain periods.
Finally, to calculate the closing win/loss average each season, simply use period.apply() on the win_loss column of your data, specifying the close dates as the index, and mean as the function.
The redsox_xts object is available in your workspace.
Cet exercice fait partie du cours
Case Study: Analyzing City Time Series Data in R
Instructions
- Use
ifelseto calculatewin_loss, which is coded as a1ifboston_scoreis greater thanopponent_scoreand a0otherwise. - Use
endpoints()to identify the date of the last game in each season. Because baseball seasons are contained in a single year, you can specify theonargument to"years"to give you the final game each year. Save these dates asclose. - Use
period.apply()to calculate the win/loss average at the close of the season. Specify thewin_losscolumn of yourredsox_xtsdata, theclosedates as the period, andmeanas the function.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Generate a new variable coding for red sox wins
redsox_xts$win_loss <- ifelse(redsox_xts$___ > redsox_xts$___, 1, 0)
# Identify the date of the last game each season
close <- endpoints(___, on = "___")
# Calculate average win/loss record at the end of each season
period.apply(redsox_xts[, "___"], ___, ___)