ma: A simple centered moving average function.

View source: R/utils.R

maR Documentation

A simple centered moving average function.

Description

This function is defined based on a code chunk found here. This is a centered moving average of arbitrary width.

Usage

ma(x, n = 5)

Arguments

x

numeric. Vector to produce a moving average of.

n

integer. The width of the moving average. Default 5 time steps.

Details

NA values are used as padding on the left and right to make the returned vector of equal length.

Value

Numeric vector of same length as x.

Examples

x  <- runif(100)
xx <- cumsum(x)
## Not run: 
plot(x)
lines(ma(x))
lines(ma(x),9)

## End(Not run)
# some de facto unit tests:
x <- 1:10
d2 <- ma(x,2) - x
d3 <- ma(x,3) - x
d4 <- ma(x,4) - x
d5 <- ma(x,5) - x
# pop <- sample.int(10, 5, replace = T)
# all should give same for linear data.
stopifnot(all(abs(d2) < 1e-10, na.rm = TRUE))
stopifnot(all(abs(d3) < 1e-10, na.rm = TRUE))
stopifnot(all(abs(d4) < 1e-10, na.rm = TRUE))
stopifnot(all(abs(d5) < 1e-10, na.rm = TRUE))

timriffe/DemoTools documentation built on Jan. 28, 2024, 5:13 a.m.