Get startedGet started for free

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

View Course

Exercise instructions

  • 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.

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)
Edit and Run Code