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.
Bài tập này là một phần của khóa học
Case Study: Analyzing City Time Series Data in R
Hướng dẫn bài tập
- Subset your
sportsdata to include only data from games played in Boston (homegame = 1) using thedata[column == x]format. Save this new object ashomegames. - Use
rollapply()to calculate the win/loss average of the last 20 homegames by Boston sports teams. You'll need to specify thewin_losscolumn of yourhomegamesdata, set thewidthto20, and set theFUNargument tomean. Save this indicator to yourhomegamesobject aswin_loss_20. - Use a similar call to
rollapply()to calculate a100game moving win/loss average. Save this indicator to yourhomegamesobject aswin_loss_100. - Use
plot.zoo()to visualize both indicators. Be sure to select thewin_loss_20andwin_loss_100columns and set theplot.typeargument to"single"to view both in the same panel. Leave theltyandlwdarguments as they are.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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)