開始使用免費開始

產生每月平均值

雖然 to.period() 指令在許多情境下很實用,但就你的需求而言,選取單一列作為整個月份的代表可能不太理想。

相較之下,每個月產生平均氣溫會更合理。為了做到這點,你需要手動使用 split()lapply() 計算每月平均,然後用 as.xts() 產生新的 xts 物件。這流程看似繁瑣,不過你已經具備完成它的能力!

先前練習篩選出的 xts 物件 temps_xts_2 已預先載入到你的工作區。另一個預先載入的 index 物件,包含資料涵蓋期間中每個月第一天的日期向量。

本練習屬於課程

個案研究:在 R 中分析城市時間序列資料

檢視課程

練習說明

  • 使用 split()temps_xts_2 物件中的 mean 欄為來源,依月份產生清單。請將期間(引數 f)指定為 "months"
  • 使用 lapply() 計算「mean 的平均」,也就是每個月的平均 mean 氣溫。
  • 使用 as.xts() 產生一個新的 xts 物件,內容為 2010 至 2015 年波士頓的每月平均氣溫。為此,你需要把每月的 mean_of_means 資料與每月的 index 物件結合。
  • 最後,確認新的 temps_monthly 物件在時間跨度與週期性上與 flights_xts 相同。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Split temps_xts_2 into separate lists per month
monthly_split <- split(___$___ , f = "___")

# Use lapply to generate the monthly mean of mean temperatures
mean_of_means <- lapply(___, FUN = ___)

# Use as.xts to generate an xts object of average monthly temperature data
temps_monthly <- as.xts(as.numeric(___), order.by = ___)
 
# Compare the periodicity and duration of your new temps_monthly and flights_xts 
periodicity(___)
periodicity(___)
編輯並執行程式碼