10

我有一个不规则的时间序列(xtsin R),我想对其应用一些时间窗。例如,给定如下的时间序列,我想计算每个离散的 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

感谢您的任何指导。

4

1 回答 1

11

用于align.time将索引s放入您感兴趣的时段。然后用于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)
于 2011-09-27T16:02:50.333 回答