movingSum: movingSum

View source: R/stat.R

movingSumR Documentation

movingSum

Description

Calculate moving sum of n values "around" values

Usage

movingSum(x, n, na.rm = FALSE)

Arguments

x

vector of values of which moving sum is to be calculated

n

number of values "around" the values in x, including the values in x, of which the mean is calculated. Only odd numbers 1, 3, 5, ... allowed. For each x[i] in x the moving sum is calculated by: x[i-(n-1)/2] + ... + x[i-1] + x[i] + x[i+1] + ... + x[i+(n-1)/2]

na.rm

logical. Should missing values (including NaN) be omitted from the calculations?

Value

Vector of moving sums with the same number of values as there are in x. If na.rm is FALSE, the first (n-1)/2 values and the last (n-1)/2 values are NA since there are not enough values at the start and at the end of the vector, respectively, to calculate the sum.

Examples

x <- rnorm(30)

plot(x, type = "b", main = "Moving mean over 3, 5, 7 points")

times <- 2:4

for (i in times) {

  lines(movingSum(x, n = 2 * i - 1), col = i, type = "b", lwd =  2)
}

legend("topright", fill = times, legend = sprintf("n = %d", 2 * times - 1))


KWB-R/kwb.utils documentation built on April 1, 2024, 7:12 a.m.