[R] moving average and NA values
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Dec 10 16:57:42 CET 2007
rollapply in the zoo package can do that:
> library(zoo)
> x <- zoo(1:10)
> x[5] <- NA
> rollapply(x, 3, mean, na.rm = TRUE)
2 3 4 5 6 7 8 9
2.0 3.0 3.5 5.0 6.5 7.0 8.0 9.0
> xm <- rollapply(x, 3, mean, na.rm = TRUE)
> xm
2 3 4 5 6 7 8 9
2.0 3.0 3.5 5.0 6.5 7.0 8.0 9.0
> coredata(xm) # unzoo it
[1] 2.0 3.0 3.5 5.0 6.5 7.0 8.0 9.0
See the two zoo vignettes for more info.
On Dec 10, 2007 6:45 AM, Cornelis de Gier <cwdegier at gmail.com> wrote:
> The S-plus function moving.ave(data, span = 2) calculates the moving
> average, but it does not have an argument to tell it how to deal with
> NA values, so it will return NA for all averages as shown below.
>
> Is there an R or S moving average function which is able to omit some
> NA values in the dataset?
>
> In the simple sample shown below it would be possible to just remove
> the rows with NA values. The dataset on which I want to use the moving
> average function with a span of 270 is a time series dataset, just
> removing rows would corrupt this dataset and make it unfit to plot.
>
> Cornelis
>
> t <- (1:10)
> moving.ave(t,2)
> $aves:
> [1] 1.0 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5
>
> $sizes:
> [1] 1 2 2 2 2 2 2 2 2 2
>
> t[5] <- NA
> moving.ave(t,2)
> $aves:
> [1] NA NA NA NA NA NA NA NA NA NA
>
> $sizes:
> [1] 1 2 2 2 2 2 2 2 2 2
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list