roll_mean: Rolling Means

Description Usage Arguments Value Examples

View source: R/roll.R

Description

A function for computing the rolling and expanding means of time-series data.

Usage

1
2
roll_mean(x, width, weights = rep(1, width), min_obs = width,
  complete_obs = FALSE, na_restore = FALSE, online = TRUE)

Arguments

x

vector or matrix. Rows are observations and columns are variables.

width

integer. Window size.

weights

vector. Weights for each observation within a window.

min_obs

integer. Minimum number of observations required to have a value within a window, otherwise result is NA.

complete_obs

logical. If TRUE then rows containing any missing values are removed, if FALSE then each value is used.

na_restore

logical. Should missing values be restored?

online

logical. Process observations using an online algorithm.

Value

An object of the same class and dimension as x with the rolling and expanding means.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
n <- 15
x <- rnorm(n)
weights <- 0.9 ^ (n:1)

# rolling means with complete windows
roll_mean(x, width = 5)

# rolling means with partial windows
roll_mean(x, width = 5, min_obs = 1)

# expanding means with partial windows
roll_mean(x, width = n, min_obs = 1)

# expanding means with partial windows and weights
roll_mean(x, width = n, min_obs = 1, weights = weights)

Example output

 [1]         NA         NA         NA         NA -0.2396745  0.0640128
 [7]  0.2456744  0.4728176  0.6727263  0.7060064  0.4651974  0.1443412
[13]  0.1169212 -0.4788303 -0.3842759
 [1]  0.3082814 -0.1550928 -0.3036490 -0.3007394 -0.2396745  0.0640128
 [7]  0.2456744  0.4728176  0.6727263  0.7060064  0.4651974  0.1443412
[13]  0.1169212 -0.4788303 -0.3842759
 [1]  0.30828139 -0.15509275 -0.30364897 -0.30073935 -0.23967446  0.10472423
 [7]  0.13116948  0.18164261  0.24007492  0.23316599  0.26857569  0.13665770
[13]  0.15674974 -0.01667693  0.02735203
 [1]  0.30828139 -0.17948086 -0.33493494 -0.32245328 -0.24259237  0.19904040
 [7]  0.21644504  0.27236974  0.34340764  0.31693499  0.36149087  0.12793457
[13]  0.16412589 -0.15164801 -0.05148473

roll documentation built on July 13, 2020, 5:09 p.m.