【发布时间】:2023-05-03 19:51:01
【问题描述】:
我有像这样的某些月份的时间序列 xts 对象
library(xts)
seq<- seq(as.POSIXct("2015-09-01"),as.POSIXct("2015-09-04"), by = "30 mins")
ob<- xts(data.frame(power=1:(length(seq))),seq)
现在,对应于每个观察(比如A),我想计算最后两个小时观察的平均值。因此,对应于每个观察(A)我需要计算两个小时前发生的观察的索引到A,比如说它是B。然后我可以计算A 和B 之间观察值的平均值。因此,
i=10 # dummy
ind_cur<- index(ob[i,]) # index of current observation
ind_back <- ind_cur - 3600 * 2 # index of 2 hours back observation
有了这些索引,我将 ob 子集化为
ob['ind_cur/ind_back']
这会导致以下错误:
Error in if (length(c(year, month, day, hour, min, sec)) == 6 && c(year, :
missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In as_numeric(YYYY) : NAs introduced by coercion
2: In as_numeric(MM) : NAs introduced by coercion
3: In as_numeric(DD) : NAs introduced by coercion
4: In as_numeric(YYYY) : NAs introduced by coercion
5: In as_numeric(MM) : NAs introduced by coercion
6: In as_numeric(DD) : NAs introduced by coercion
谁能帮我把ob子集化!在link找到了一个相关的问题,但是还不足以解决这个问题。
更新预期输出显示为
2015-09-01 00:00:00 1 NA # as I don't have previous data
2015-09-01 00:30:00 2 NA
2015-09-01 01:00:00 3 NA
2015-09-01 01:30:00 4 NA
2015-09-01 02:00:00 5 10/4 # mean of prevous 4 observations (last two hours)
2015-09-01 02:30:00 6 14/4
2015-09-01 03:00:00 7 18/4
【问题讨论】:
-
预期输出是什么?
-
这和移动平均线不一样吗?为此,您可以使用 TTR 包中定义的 SMA 函数。此外,在您当前的实现中,索引
'ind_cur/ind_back'将被视为字符串文字,不会扩展到实际日期。
标签: r time-series xts