문제

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