計算時間序列趨勢
xts 物件的一大優點,是能在時間軸上直接進行簡單的數學運算。在你的航班資料中,一個很實用的指標是:每個月延誤、取消或改降(改道)航班的比例。
在這個練習中,你會用資料產生一個新的時間序列欄位,內容是每個月抵達波士頓的延誤航班比例。接著你會為這個指標畫圖,然後再計算航班取消與改降的其他指標。
本練習屬於課程
個案研究:在 R 中分析城市時間序列資料
練習說明
- 在
flights_xts上使用簡單的數學運算,計算每個月延誤航班的百分比。將結果儲存為flights_xts中名為pct_delay的新欄位。 - 使用
plot.xts()檢視每個月延誤航班的百分比。 - 依照同樣的計算方式,在 xts 物件中再新增兩個欄位:
pct_cancel與pct_divert,分別代表取消與改降的航班比例。 - 使用
plot.zoo()一次檢視這三個趨勢。為此,你需要在flights_xts中擷取只包含剛剛產生的三個欄位的子集。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate percentage of flights delayed each month: pct_delay
flights_xts$pct_delay <- (___ / ___) * 100
# Use plot.xts() to view pct_delay over time
# Calculate percentage of flights cancelled each month: pct_cancel
# Calculate percentage of flights diverted each month: pct_divert
# Use plot.zoo() to view all three trends over time
plot.zoo(x = ___[ , c("___", "___", "___")])