Get startedGet started for free

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

View Course

Exercise instructions

  • Use ifelse to calculate win_loss, which is coded as a 1 if boston_score is greater than opponent_score and a 0 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 the on argument to "years" to give you the final game each year. Save these dates as close.
  • Use period.apply() to calculate the win/loss average at the close of the season. Specify the win_loss column of your redsox_xts data, the close dates as the period, and mean 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[, "___"], ___, ___)
Edit and Run Code