Question

I got a question about applying rollmean function to a vector with a long NA's in the middle. Here is an example.

> (z <- c(sample (x=1:10, size=5), rep (x=NA, times=5), sample (x=1:10, size=5)))
[1]  1  7  8  3  5 NA NA NA NA NA  3  5 10  8  4
> rollmean (x=zoo (z, 1:length(z)), k=3)
     2        3        4        5        6        7        8        9       10       11       12       13       14 
5.333333 6.000000 5.333333       NA       NA       NA       NA       NA       NA       NA       NA       NA       NA
> rev (rollmean (x=zoo (rev (z), 1:length (z)), k=3))
     2        3        4        5        6        7        8        9       10       11       12       13       14 
     NA       NA       NA       NA       NA       NA       NA       NA       NA       NA 6.000000 7.666667 7.333333

so how could I get the answer like this

2        3        4        5        6        7        8        9       10       11       12       13       14 
5.333333 6.000000 5.333333       NA       NA       NA       NA       NA       NA       NA 6.000000 7.666667 7.333333

thanks.

Était-ce utile?

La solution

My understanding is rollmean is an optimized version of rollapply with mean as the function. If you don't need the added performance you can try the following which works

z = c(1,7,8,3,5,NA,NA,NA,NA,NA,3,5,10,8,4)
x = zoo (z, 1:length(z))
rollapply(x,3,mean)
2        3        4        5        6        7        8        9       10       11       12       13       14 
5.333333 6.000000 5.333333       NA       NA       NA       NA       NA       NA       NA 6.000000 7.666667 7.333333 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top