Using rollapply to process time window -- not fixed sample window for irregular time series

498 views Asked by At

I am trying to compute various stats for a time window (think 20 seconds) for various signals which may or may not be recorded at every sample window. Additionally, the sampling interval is not regular -- it may be 2 or 3 or 4 seconds. Consider where t is the elapsed seconds of the experiment and d is the measurement:

require('zoo')

t<- c( 0, 1, 2, 4, 5, 6, 9, 10 )
d<- c( 2, 2, 2, 4, 4, 4, 8, 10 )
z<- zoo(d, t)

Now, as you see, there are no measurements at 3, 7, or 8 seconds. I would like to compute something like the max value in a 3 second window. Ideally my output would be like

NA, 2, 2, 4, 4, 4, 8, NA

(I don't need the NAs -- just trying to make the example clear.) trying:

rollapply( z, 3, max)
 1  2  4  5  6  9 
 2  4  4  4  8 10 

Not quite what I'm looking for! Consider the rollapply result at t[3]. This should be 2 not 4 as the non-existent measure at 3s is IN the window, but the existing measurement at 4s is NOT. It "looks" like the results are just shifted, but you can play around with other numbers and realize it's just plain wrong.

I'm a noob to zoo, but fairly experienced in signal processing. Can't quite seem to get this to do what I need.

Thanks in advance.

1

There are 1 answers

0
G. Grothendieck On

Fill in the series with NAs at the missing points using a grid g and then use rollapplyr to right align the window (the default for rollapply is center alignment):

library(zoo)

g <- seq(start(z), end(z), 1.0)
zz <- merge(z, zoo(, g))
rollapplyr(zz, 3, max, na.rm = TRUE)

giving:

 2  3  4  5  6  7  8  9 10 
 2  2  4  4  4  4  4  8 10