roll_sd: Rolling Standard Deviations

Description Usage Arguments Details Value Examples

View source: R/roll.R

Description

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

Usage

1
2
3
roll_sd(x, width, weights = rep(1, width), center = TRUE,
  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.

center

logical. If TRUE then the weighted mean of each variable is used, if FALSE then zero is used.

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.

Details

The denominator used gives an unbiased estimate of the standard deviation, so if the weights are the default then the divisor n - 1 is obtained.

Value

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

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 standard deviations with complete windows
roll_sd(x, width = 5)

# rolling standard deviations with partial windows
roll_sd(x, width = 5, min_obs = 1)

# expanding standard deviations with partial windows
roll_sd(x, width = n, min_obs = 1)

# expanding standard deviations with partial windows and weights
roll_sd(x, width = n, min_obs = 1, weights = weights)

Example output

 [1]        NA        NA        NA        NA 1.1572734 1.0625719 1.2737189
 [8] 1.1811277 1.2416773 1.1380419 0.9522332 0.8622448 0.7689775 1.0673762
[15] 1.0801291
 [1]        NA 1.2582516 1.1402339 0.9317385 1.1572734 1.0625719 1.2737189
 [8] 1.1811277 1.2416773 1.1380419 0.9522332 0.8622448 0.7689775 1.0673762
[15] 1.0801291
 [1]        NA 1.2582516 1.1402339 0.9317385 1.1572734 1.0609663 1.1658941
 [8] 1.1174088 1.0722261 1.1220850 1.0931397 1.0465994 1.0271691 1.0392800
[15] 1.0948314
 [1]        NA 1.2582516 1.1515474 0.9159258 1.1829929 1.0522295 1.2097719
 [8] 1.1393711 1.0755546 1.1438555 1.0870277 1.0074694 0.9929896 1.0276670
[15] 1.1240393

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