How do I match data frames by time intervals?

ぃ、小莉子 提交于 2019-12-03 08:24:52

Use align.time in xts.

library(xts)
xTemps <- align.time(xts(temps[,2],as.POSIXct(temps[,1])), n=600)
xGas <- align.time(xts(gas[,2],as.POSIXct(gas[,1])), n=600)
merge(xTemps,xGas)

Use either one of zoo or xts to hold your data -- their merge() function will do this for you. You can look for previous answers here. The zoo documentation has also lots of relevant examples.

Here is a mock-up example:

> set.seed(42)
> temps <- zoo(78+rnorm(5), 
+              order.by=ISOdatetime(2010,9,30,6,58,53)+cumsum(60*runif(5)))
> gas <- zoo(sample(1:5,5), 
+            order.by=ISOdatetime(2010,9,30,6,58,53)+cumsum(60*runif(5)))
> merge(temps,gas)
                     temps gas
2010-09-30 06:59:47 78.048  NA
2010-09-30 06:59:49     NA   5
2010-09-30 07:00:44 76.895  NA
2010-09-30 07:00:48     NA   1
2010-09-30 07:00:55     NA   3
2010-09-30 07:01:01 78.539  NA
2010-09-30 07:01:23     NA   2
2010-09-30 07:01:51 78.580  NA
2010-09-30 07:01:57     NA   4
2010-09-30 07:02:29 77.342  NA
> na.locf(merge(temps,gas))
                     temps gas
2010-09-30 06:59:49 78.048   5
2010-09-30 07:00:44 76.895   5
2010-09-30 07:00:48 76.895   1
2010-09-30 07:00:55 76.895   3
2010-09-30 07:01:01 78.539   3
2010-09-30 07:01:23 78.539   2
2010-09-30 07:01:51 78.580   2
2010-09-30 07:01:57 78.580   4
2010-09-30 07:02:29 77.342   4
> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!