Exercise

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

Instructions

**100 XP**

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