開始使用免費開始

失業率的差分

除了為資料加入落後期,你也可以透過產生此序列的差分來輔助分析。

若要計算差分,直接使用 diff() 指令。這個指令需要你指定原始資料物件、落後期數(lag),以及差分的階數(differences)。

在本練習中,你會以不同的方式擴充 unemployment,加入幾個實用的差分指標。

本練習屬於課程

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

檢視課程

練習說明

  • 使用 diff() 建立美國失業率的一階每月差分。在呼叫 diff() 時,請在 unemployment 中指定取用的欄位,並提供 lagdifferences 參數。不要先存成要合併的新物件,而是直接將結果存成 unemployment 的新欄位 us_monthlydiff
  • 以相同方式呼叫 diff(),建立美國失業率的「年度」差分。將結果存到 unemployment$us_yearlydiff
  • 使用兩次 plot.xts(),分別繪製美國失業率(unemployment$us)與年度變動(unemployment$us_yearlydiff)的圖。第二次呼叫 plot.xts() 時,維持現有的 type 參數設定,以產生長條圖。事先寫好的 par() 指令能讓你同時檢視這兩張圖。

動手互動練習

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

# Generate monthly difference in unemployment
unemployment$us_monthlydiff <- diff(___$___, lag = ___, differences = ___)

# Generate yearly difference in unemployment
unemployment$us_yearlydiff <- 

# Plot US unemployment and annual difference
par(mfrow = c(2,1))
plot.xts(___)
plot.xts(___, type = "h")
編輯並執行程式碼