使用 merge() 並繪製時間序列圖
現在你已經有與航班資料同一期間(2010-2015)且同一頻率(每月)的氣溫資料,可以開始合併了。
若要依欄合併 xts 物件,你可以使用 merge()。當兩個 xts 物件具有相同的週期性時,merge() 通常能把資訊對應到正確的列。即使兩個 xts 物件的週期性不同,merge() 也會在不同期間之間保留正確的時間順序。
在這個練習中,你會將兩個 xts 物件依欄合併,並產生新圖表來探索航班延誤與氣溫的關係。temps_monthly 與 flights_xts 已經在你的工作環境中。
本練習屬於課程
個案研究:在 R 中分析城市時間序列資料
練習說明
- 使用
merge()合併flights_xts與temps_monthly。因為這些 xts 物件具有相同的週期性,你的合併指令應該會把氣溫資料放到flights_xts中對應的列。請注意,你列出要合併物件的順序會決定合併後欄位出現的位置。為了保持一致,請先放入flights_xts,再放入temps_monthly。 - 檢視合併後 xts 物件(
flights_temps)的前幾列,確認合併是否成功。你應該會看到氣溫資料與航班資料對齊。 - 使用
plot.zoo()產生單一圖,包含flights_temps中的pct_delay與temps_monthly兩個欄位。記得只取相關欄位,並將plot.type指定為"single"。lty參數維持原樣即可。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Use merge to combine your flights and temperature objects
flights_temps <- merge(___, ___)
# Examine the first few rows of your combined xts object
# Use plot.zoo to plot these two columns in a single panel
plot.zoo(___[,c("___", "___")], plot.type = "___", lty = lty)
legend("topright", lty = lty, legend = labels, bg = "white")