简体   繁体   中英

Constant-size period.apply with irregularly spaced endpoints in R

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.

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

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.

重叠间隔

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM