Get startedGet started for free

Calculate and plot a rolling average

The final baseball indicator you'd like to generate is the L10, or the moving win/loss average from the previous ten games. While the cumulative win/loss average tells you how the team is doing overall, the L10 indicator provides a more specific picture of the team's recent performance. Beyond the world of sports, this measure is comparable to a financial indicator focused on recent portfolio performance.

To generate a rolling win/loss average, return to the rollapply() command used in the previous chapter. In this case, you'll want to apply the mean function to the last 10 games played by the Red Sox at any given time during the 2013 season.

The redsox_xts object, including the win_loss column, is available in your workspace.

This exercise is part of the course

Case Study: Analyzing City Time Series Data in R

View Course

Exercise instructions

  • Generate a new xts object containing only the 2013 season. Call this object redsox_2013.
  • Use rollapply() to calculate your lastten_2013 indicator based on the win_loss column in redsox_2013. Set the width equal to 10 to include the last ten games played by the Red Sox and set the FUN argument to mean to generate an average of the win_loss column.
  • Use plot.xts() to view your new indicator during the 2013 season. Leave the ylim argument as is in the prewritten code.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Select only the 2013 season
redsox_2013 <- ___["___"]

# Use rollapply to generate the last ten average
lastten_2013 <- rollapply(___$___, width = ___, FUN = ___)

# Plot the last ten average during the 2013 season
plot.xts(___, ylim = c(0, 1))
Edit and Run Code