恒定大小的周期。在R中具有不规则间隔的端点

时间:2020-12-05 18:38:01

I have an irregular time series contained in xts and separate time index vector (endpoints). I want to calculate statistics for every index point based on preceding 5 seconds for every endpoint. So, starting point should be 5 seconds before every endpoint. These periods may overlap.

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

I cannot find any function from *apply family doing that job. How can I do that? Should I manually write loop for it?

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

Here is my humble illustration where black is xts data and red are endpoints. I want to have a result of a function for every red point calculated on all black points in 5-seconds interval.

这是我的简单插图,其中黑色是xts数据,红色是端点。我希望在5秒间隔内对所有黑点计算的每个红点都有一个函数的结果。

恒定大小的周期。在R中具有不规则间隔的端点

1 个解决方案

#1


1  

There isn't a ready-made function to do this, but it's fairly easy to write your own.

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

# 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))

#1


1  

There isn't a ready-made function to do this, but it's fairly easy to write your own.

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

# 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))