Skip to content

moving average and NA values

2 messages · Cornelis de Gier, Gabor Grothendieck

#
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
#
rollapply in the zoo package can do that:
2   3   4   5   6   7   8   9
2.0 3.0 3.5 5.0 6.5 7.0 8.0 9.0
2   3   4   5   6   7   8   9
2.0 3.0 3.5 5.0 6.5 7.0 8.0 9.0
[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: