開始使用免費開始

失業率的滯後處理

由於經濟趨勢可能需要一段時間才會影響觀光業,在分析之前先對失業率資料做滯後可能會有幫助。

在 xts 中使用 lag() 產生滯後相當直接,你需要指定要滯後的資料(參數 x),以及用來決定滯後方向與幅度的 k 值。

請特別留意不同函式庫的格式差異。Base R 與 zoo 套件要求以「負值」指定滯後,因此 1 期滯後要寫成 "-1"(而 1 期前置 lead 則反直覺地寫成 "1")。相較之下,xts 套件以「正值」指定滯後,因此 1 期滯後寫成 "1"(而 1 期前置則寫成 "-1")。

本練習屬於課程

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

檢視課程

練習說明

  • 使用 lag() 產生「美國失業率」的 1 個月滯後。對月度資料的一個月滯後,將參數 k 設為 1 即可。記得 unemployment 物件同時包含美國失業率(us)與麻州失業率(ma),你需要指定要滯後的欄位。將新的 xts 物件存為 us_monthlag
  • 再次呼叫 lag(),產生「美國失業率」的 1 年滯後。同樣地,確認在 unemployment 中指定正確欄位,並設定適當的 k 值來產生整整 1 年的滯後。將新的 xts 物件存為 us_yearlag
  • 使用 merge() 將原始失業率資料(unemployment)與新產生的滯後(us_monthlagus_yearlag)合併。將合併後的資料存為 unemployment_lags
  • 使用 head() 檢視 unemployment_lags 的前 15 列。

動手互動練習

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

# Create a one month lag of US unemployment
us_monthlag <- lag(___$___, k = ___)

# Create a one year lag of US unemployment
us_yearlag <- 

# Merge your original data with your new lags 
unemployment_lags <- merge(unemployment, ___, ___)

# View the first 15 rows of unemployment_lags
編輯並執行程式碼