Calculate a rolling average across all sports
Now that you've mastered subsetting your data to include only weekend games, your client would like you to take a different approach. Perhaps Boston's tourism industry receives a boost when local sports teams win more games at home.
Instead of focusing on weekend games, you are tasked with generating a rolling win/loss average focused on games played in Boston. To produce this indicator, you'll return to the rollapply()
command used above, this time applying your calculation to all Boston-area sports teams but subsetting to include only games played at home.
This exercise is part of the course
Case Study: Analyzing City Time Series Data in R
Exercise instructions
- Subset your
sports
data to include only data from games played in Boston (homegame = 1
) using thedata[column == x]
format. Save this new object ashomegames
. - Use
rollapply()
to calculate the win/loss average of the last 20 homegames by Boston sports teams. You'll need to specify thewin_loss
column of yourhomegames
data, set thewidth
to20
, and set theFUN
argument tomean
. Save this indicator to yourhomegames
object aswin_loss_20
. - Use a similar call to
rollapply()
to calculate a100
game moving win/loss average. Save this indicator to yourhomegames
object aswin_loss_100
. - Use
plot.zoo()
to visualize both indicators. Be sure to select thewin_loss_20
andwin_loss_100
columns and set theplot.type
argument to"single"
to view both in the same panel. Leave thelty
andlwd
arguments as they are.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Generate a subset of sports data with only homegames
homegames <- sports[sports$___ == ___]
# Calculate the win/loss average of the last 20 home games
homegames$win_loss_20 <- rollapply(___$___, width = ___, FUN = ___)
# Calculate the win/loss average of the last 100 home games
homegames$win_loss_100 <-
# Use plot.xts to generate
plot.zoo(___[, c("___", "___")], plot.type = "___", lty = lty, lwd = lwd)