Description Usage Arguments Details Value Author(s) See Also Examples
A way to calculate a moving average.
1 | movingAverage(x, n = 1, centered = FALSE)
|
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.) |
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.
sum divided by count
Cookbook, R. winston@stdout.org
http://www.cookbook-r.com/Manipulating_data/Calculating_a_moving_average/
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)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.