roll_cor: Rolling Correlations

Description Usage Arguments Details Value Examples

View source: R/roll.R

Description

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

Usage

1
2
3
roll_cor(x, y = NULL, width, weights = rep(1, width), center = TRUE,
  scale = TRUE, min_obs = width, complete_obs = TRUE,
  na_restore = FALSE, online = TRUE)

Arguments

x

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

y

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.

scale

logical. If TRUE then the weighted standard deviation of each variable is used, if FALSE then no scaling is done.

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 pairwise 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 covariance, so if the weights are the default then the divisor n - 1 is obtained.

Value

A cube with each slice the rolling and expanding correlations.

Examples

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

# rolling correlations with complete windows
roll_cor(x, y, width = 5)

# rolling correlations with partial windows
roll_cor(x, y, width = 5, min_obs = 1)

# expanding correlations with partial windows
roll_cor(x, y, width = n, min_obs = 1)

# expanding correlations with partial windows and weights
roll_cor(x, y, width = n, min_obs = 1, weights = weights)

Example output

 [1]          NA          NA          NA          NA  0.33724365  0.28865402
 [7]  0.04487921  0.16373152  0.64587810  0.50501936  0.42060940  0.32096086
[13]  0.41331235  0.38439764 -0.39328160
 [1]          NA  1.00000000  0.98403738  0.96306904  0.33724365  0.28865402
 [7]  0.04487921  0.16373152  0.64587810  0.50501936  0.42060940  0.32096086
[13]  0.41331235  0.38439764 -0.39328160
 [1]          NA  1.00000000  0.98403738  0.96306904  0.33724365  0.31060262
 [7]  0.31094543  0.26501712  0.27940252  0.29583840  0.30046228  0.29792730
[13]  0.30018483  0.32551590 -0.02714091
 [1]         NA  1.0000000  0.9858100  0.9611817  0.2637626  0.2783842
 [7]  0.2827871  0.2430799  0.2628369  0.2779203  0.2923160  0.2883164
[13]  0.2914858  0.3328589 -0.2241375

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