我有一个不规则的时间序列(xts
中的R
),我想对其应用一些时间窗口。例如,给定一个类似以下的时间序列,我想计算一些事情,例如从2009-09-22 00:00:00
开始的每个离散的3小时窗口中有多少个观测值:
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
感谢您的指导。
最佳答案
使用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)
关于对不规则时间序列进行定期分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7571788/