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.
This exercise is part of the course
Case Study: Analyzing City Time Series Data in R
Exercise instructions
- Use
ifelse
to calculatewin_loss
, which is coded as a1
ifboston_score
is greater thanopponent_score
and a0
otherwise. - 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 theon
argument 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_loss
column of yourredsox_xts
data, theclose
dates as the period, andmean
as the function.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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[, "___"], ___, ___)