Apply rollmean function to a vector with a long NA's in the middle

StackOverflow https://stackoverflow.com/questions/19172623

  •  30-06-2022
  •  | 
  •  

سؤال

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.

هل كانت مفيدة؟

المحلول

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 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top