開始使用免費開始

使用 rbind() 合併

現在你已經了解溫度資料的結構與範圍,下一步是把這些物件轉成 xts,並用 rbind() 合併。

在把物件轉成 xts 之前,你需要先找出將作為時間索引的欄位,並確認它已編碼為時間型別物件。在這裡,你要檢查 temps_1temps_2date 欄位的類別。一旦確認合適的時間型索引後,就可以把兩個物件都編碼成 xts,接著依列進行合併。

temps_1temps_2 物件已在你的工作環境中,且已為你載入 xts 套件。

本練習屬於課程

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

檢視課程

練習說明

  • 以兩次呼叫 class() 檢查 temps_1temps_2date 欄位是否為時間型別物件(Date、POSIXct、POSIXlt、yearmon 等)。
  • 使用 as.xts() 將兩個溫度資料框(temps_1temps_2)各自編碼為 xts 物件。請務必在 order.by 參數指定相關的時間型欄位,並記得用 data[, -column] 的寫法移除時間欄位。
  • 以兩次呼叫 head() 確認新的 xts 物件格式正確。
  • 對這兩個 xts 物件使用 rbind(),將它們合併為單一物件:temps_xts
  • 結合 first()last(),找出 temps_xts 中「第 1 年裡最後 1 個月的前 3 天」的資料。

動手互動練習

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

# Confirm that the date column in each object is a time-based class
class(___)
class(___)

# Encode your two temperature data frames as xts objects
temps_1_xts <- as.xts(___[, -4], order.by = ___)
temps_2_xts <- ___

# View the first few lines of each new xts object to confirm they are properly formatted
head(___)
head(___)

# Use rbind to merge your new xts objects
temps_xts <- ___

# View data for the first 3 days of the last month of the first year in temps_xts
___(___(first(___, "1 year"), "1 month"), "___")
編輯並執行程式碼