Ken*_*ams 10 r time-series xts
我有一个不规则的时间序列(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")))
Run Code Online (Sandbox Code Playgroud)
我显然不能使用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
Run Code Online (Sandbox Code Playgroud)
谢谢你的指导.
Jos*_*ich 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1891 次 |
| 最近记录: |