計算並繪製季內平均
在上一個練習中,你使用 endpoints() 和 period.apply() 快速計算了 Boston Red Sox 每一季結束時的勝負平均。不過,如果你想知道每一季「過程中」的累積平均呢?統計學家與球迷常用這個平均來比較一支球隊與其對手的表現。
若要計算每一季的累積平均,你需要回到第 3 章練習過的 split-lapply-rbind 公式。首先,以球季分割資料,接著在每一季對 win_loss 欄位套用累積平均函式,最後再把結果合併回一個 xts 物件。
我們已為你準備自訂的 cummean() 函式,它會先計算累積總和,然後除以累積中包含的筆數。redsox_xts 資料(包含 win_loss 欄位)已載入到你的工作環境中。
本練習屬於課程
個案研究:在 R 中分析城市時間序列資料
練習說明
- 使用
split()依球季(此處為years)切分redsox_xts資料。指定為redsox_seasons。 - 使用
lapply()計算每一季的累積平均。本練習已提供cummean()函式,會以cumsum()計算總和,再以seq_along()表示的筆數去除。將結果存為redsox_ytd。 - 使用
do.call()搭配rbind,把你的清單輸出轉成單一 xts 物件(redsox_winloss),其中包含各季過程中的勝負平均。 - 使用
plot.xts()檢視2013球季期間的累積勝負平均。請保留你預先寫好的程式碼中ylim參數的設定。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Split redsox_xts win_loss data into years
redsox_seasons <- split(___$___, f = "___")
# Use lapply to calculate the cumulative mean for each season
redsox_ytd <- lapply(___, cummean)
# Use do.call to rbind the results
redsox_winloss <- do.call(___, ___)
# Plot the win_loss average for the 2013 season
plot.xts(___["___"], ylim = c(0, 1))