Question

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.

overlapping intervals

Was it helpful?

Solution

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top