2

我有一个不规则的时间序列包含在 xts 和单独的时间索引向量(端点)中。我想根据每个端点的前 5 秒计算每个索引点的统计信息。因此,起点应在每个终点前 5 秒。这些时期可能会重叠。

我找不到 *apply family 的任何功能来做这项工作。我怎样才能做到这一点?我应该为它手动编写循环吗?

这是我的简陋插图,黑色是 xts 数据,红色是端点。我希望以 5 秒的间隔在所有黑点上计算每个红点的函数结果。

重叠区间

4

1 回答 1

1

没有现成的函数可以做到这一点,但编写自己的函数相当容易。

# Example data
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
# Example function
# Calculate the mean of the last 5 days of each month, returning
# an xts object indexed at the endpoint
myFunction <- function(i, y) xts(t(colMeans(y[(i-4):i,])), index(y)[i])
# Use lapply to call your function at each endpoint
# (removing first endpoint, since it equals zero) 
do.call(rbind, lapply(endpoints(x, 'months')[-1], FUN=myFunction, y=x))
于 2012-04-03T12:02:18.887 回答