1. Learn
  2. /
  3. Courses
  4. /
  5. Case Study: Analyzing City Time Series Data in R

Exercise

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.

Instructions

100 XP
  • Subset your sports data to include only data from games played in Boston (homegame = 1) using the data[column == x] format. Save this new object as homegames.
  • Use rollapply() to calculate the win/loss average of the last 20 homegames by Boston sports teams. You'll need to specify the win_loss column of your homegames data, set the width to 20, and set the FUN argument to mean. Save this indicator to your homegames object as win_loss_20.
  • Use a similar call to rollapply() to calculate a 100 game moving win/loss average. Save this indicator to your homegames object as win_loss_100.
  • Use plot.zoo() to visualize both indicators. Be sure to select the win_loss_20 and win_loss_100 columns and set the plot.type argument to "single" to view both in the same panel. Leave the lty and lwd arguments as they are.