Skip to contents

Computes rolling linear regression slope (first derivative) for a numeric response variable y within a moving window.

Usage

rolling_slope(
  y,
  x = seq_along(y),
  span,
  align = c("center", "left", "right"),
  na.rm = FALSE
)

Arguments

y

A numeric vector of the response variable.

x

A numeric vector of the predictor variable, defaults to using the index of x = seq_along(y).

span

A numeric value defining the window in units of x for rolling local calculations.

align

Specifies the window alignment of span as "center" (the default), "left", or "right". Where "left" is forward looking, and "right" is backward looking by the window span from the current sample.

na.rm

A logical indicating how missing data will be handled. FALSE (the default) will perform complete case analysis and return the rolling slopes where all local y samples are valid. TRUE will return the rolling slopes where the local target y sample is valid.

Value

A numeric vector of rolling local slopes in units of y/x of the same length as y.

Details

Uses the least squares formula on complete case analysis to calculate local slopes within a rolling window specified by span along x, in units of x. i.e. span = 10 would include samples within a 10-second window for time series data.

See also

Examples

y <- c(1, 3, 2, 5, 8, 7, 9, 12, 11, 15, 14, 17, 18)
rolling_slope(y, span = 3)
#>  [1] 2.0 0.5 1.0 3.0 1.0 0.5 2.5 1.0 1.5 1.5 1.0 2.0 1.0
rolling_slope(y, span = 3, align = "left")
#>  [1] 1.1 1.8 1.8 1.1 1.4 1.5 1.7 1.0 1.7 1.2 2.0 1.0 0.0

y_na <- c(1, 3, NA, 5, 8, 7, 9, 12, NA, NA, NA, 17, 18)
rolling_slope(y_na, span = 3)
#>  [1] 2.0  NA  NA  NA 1.0 0.5 2.5  NA  NA  NA  NA  NA 1.0