movingAverage: Calculating a Moving Average

Description Usage Arguments Details Value Author(s) See Also Examples

Description

A way to calculate a moving average.

Usage

1
movingAverage(x, n = 1, centered = FALSE)

Arguments

x

the vector

n

the number of samples

centered

if FALSE, then average current sample and previous (n-1) samples if TRUE, then average symmetrically in past and future. (If n is even, use one more sample from future.)

Details

Suppose your data is a noisy sine wave with some missing values. A different way to handle missing data is to simply ignore it, and not include it in the average. The function defined here will do that.

Value

sum divided by count

Author(s)

Cookbook, R. winston@stdout.org

See Also

http://www.cookbook-r.com/Manipulating_data/Calculating_a_moving_average/

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Make same plots from before, with thicker lines
plot(x, y, type="l", col=grey(.5))
grid()
y_lag <- filter(y, rep(1/20, 20), sides=1)
lines(x, y_lag, col="red", lwd=4)         # Lagged average in red
y_sym <- filter(y, rep(1/21,21), sides=2)
lines(x, y_sym, col="blue", lwd=4)        # Symmetrical average in blue
# Calculate lagged moving average with new method and overplot with green
y_lag_na.rm <- movingAverage(y, 20)
lines(x, y_lag_na.rm, col="green", lwd=2)
y_sym_na.rm <- movingAverage(y, 21, TRUE)
lines(x, y_sym_na.rm, col="green", lwd=2)

fredysiegrist/statanacoseq documentation built on May 16, 2019, 2:44 p.m.