2011-09-27 59 views
9

我有一个不规则的时间序列(xtsR),我想对其应用一些时间窗口。例如,给定一个时间序列像下面,我想计算之类的东西有多少个观察有在每一个离散3小时的窗口,从2009-09-22 00:00:00开始:对不规则时间序列的定期分析

library(lubridate) 
s <- xts(c("OK", "Fail", "Service", "OK", "Service", "OK"), 
     ymd_hms(c("2009-09-22 07:43:30", "2009-10-01 03:50:30", 
        "2009-10-01 08:45:00", "2009-10-01 09:48:15", 
        "2009-11-11 10:30:30", "2009-11-11 11:12:45"))) 

我显然不能用period.apply()split()要做到这一点,因为那些会忽略没有意见的时期,我不能给它一个开始时间。

我期望的输出很简单计数的问题(虽然,当然,我真正的任务是,每段更复杂!)会是这样的,如果我汇总3天时间:

2009-09-22 1 
2009-09-25 0 
2009-09-28 0 
2009-10-01 3 
2009-10-04 0 
2009-10-07 0 
2009-10-10 0 
2009-10-13 0 
2009-10-16 0 
2009-10-19 0 
2009-10-22 0 
2009-10-25 0 
2009-10-28 0 
2009-10-31 0 
2009-11-03 0 
2009-11-06 0 
2009-11-09 2 

感谢您的任何指导。

回答

11

使用align.times的索引放入您感兴趣的期间。然后使用period.apply查找每个3小时窗口的长度。然后将它与一个空的xts对象合并,该对象具有所有您想要的索引值。

# align index into 3-hour blocks 
a <- align.time(s, n=60*60*3) 
# find the number of obs in each block 
count <- period.apply(a, endpoints(a, "hours", 3), length) 
# create an empty xts object with the desired index 
e <- xts(,seq(start(a),end(a),by="3 hours")) 
# merge the counts with the empty object and fill with zeros 
out <- merge(e,count,fill=0) 
+0

这不会做我在找的东西 - 让我给原始问题添加更多细节。 –

+0

也许'合并()'的想法是我需要的 - 但是用我想要的间隔端点创建一个序列,然后将它合并到序列中? –

+0

@KenWilliams:你在正确的轨道上。我已经更新了我的答案... –

相关问题