2014-01-09 20 views
-1

關於在R中加入時間序列表的問題...R:加入兩個時間序列

我有以下兩個數據框; 「到達」和「臨時」(見下文)。 「到達」描述到達分組的日期/時間/大小,「臨時」具有逐分鐘溫度數據。我想要做的是在「到達」中添加一列,到達$ tempAtArrivalTime,列出給定到達時間的當前溫度。例如,對於第一次到達,在8點39分04秒,我想讓相應的「tempAtArrivalTime」爲76(最近記錄的溫度,在8:39:00)。最簡單的方法是什麼?謝謝!

>arrivals 
      date  time size of arrival 
2012 2013-09-09 08:39:04    15 
2013 2013-09-09 08:43:15    3 
2014 2013-09-09 08:47:50    7 
2015 2013-09-09 08:54:47    10 

> temps 
     date  time temperature 
2013-09-09 08:33:00   76 
2013-09-09 08:34:00   75 
2013-09-09 08:35:00   74 
2013-09-09 08:36:00   75 
2013-09-09 08:37:00   76 
2013-09-09 08:38:00   76 
2013-09-09 08:39:00   76 
2013-09-09 08:40:00   76 
2013-09-09 08:41:00   77 
2013-09-09 08:42:00   78 
2013-09-09 08:43:00   77 
2013-09-09 08:44:00   78 
2013-09-09 08:45:00   77 
2013-09-09 08:46:00   77 
2013-09-09 08:47:00   77 
2013-09-09 08:48:00   77 
2013-09-09 08:49:00   78 
2013-09-09 08:50:00   79 
2013-09-09 08:51:00   80 
2013-09-09 08:52:00   80 
2013-09-09 08:53:00   79 
2013-09-09 08:54:00   78 
+0

複製的[以下問題](http://stackoverflow.com/questions/7089444/r-merge-two-irregular-time -series-解決了嗎?RQ = 1)。 Downvote由於明顯的重複,這是微不足道的查找 –

回答

1

試試這個:

library(zoo) 
arrivals.z <- read.zoo(arrivals, index = 1:2, tz = "") 
temp.z <- read.zoo(temp, index = 1:2, tz = "") 

na.locf(merge(arrivals.z, temp.z))[time(arrivals.z)] 

這給:

    arrivals.z temp.z 
2013-09-09 08:39:04   15  76 
2013-09-09 08:43:15   3  77 
2013-09-09 08:47:50   7  77 
2013-09-09 08:54:47   10  78 

注:要獲得arrivalstemp我們用這個。 (下一次請使用dput以可重現的形式提供的輸入。)

Lines1 <- " date  time size of arrival 
2012 2013-09-09 08:39:04    15 
2013 2013-09-09 08:43:15    3 
2014 2013-09-09 08:47:50    7 
2015 2013-09-09 08:54:47    10 
" 

Lines2 <- "  date  time temperature 
2013-09-09 08:33:00   76 
2013-09-09 08:34:00   75 
2013-09-09 08:35:00   74 
2013-09-09 08:36:00   75 
2013-09-09 08:37:00   76 
2013-09-09 08:38:00   76 
2013-09-09 08:39:00   76 
2013-09-09 08:40:00   76 
2013-09-09 08:41:00   77 
2013-09-09 08:42:00   78 
2013-09-09 08:43:00   77 
2013-09-09 08:44:00   78 
2013-09-09 08:45:00   77 
2013-09-09 08:46:00   77 
2013-09-09 08:47:00   77 
2013-09-09 08:48:00   77 
2013-09-09 08:49:00   78 
2013-09-09 08:50:00   79 
2013-09-09 08:51:00   80 
2013-09-09 08:52:00   80 
2013-09-09 08:53:00   79 
2013-09-09 08:54:00   78 
" 

arrivals <- read.table(text = Lines1, skip = 1)[, -1] 
temp <- read.table(text = Lines2, header = TRUE) 
+0

啊,太棒了,這幾乎正是我所期待的!唯一的錯誤...進一步下來在我的數據表中,我有重複的次數,但有不同的日期,但我得到的錯誤「merge.zoo中的錯誤(arrivals.z,temps.z): 系列不能合併與非 - 系列中唯一的索引條目「。元組(日期,時間)雖然都是唯一的。任何干淨的解決方案,而不必將我的變量融入到「日期時間」對象? – bigO6377

+0

把日期和時間放在一起是乾淨的做法。保持他們分開是凌亂的。 –