Skip to contents

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

Usage

rolling_slope(
  y,
  x = seq_along(y),
  width,
  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).

width

A numeric scalar defining the window width in units of x for rolling calculations.

align

Specifies the window alignment of width as "center" (the default), "left", or "right". Where "left" is forward looking, and "right" is backward looking by the window width 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 along x specified by width in units of x. i.e. x = 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, width = 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, width = 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, width = 3)
#>  [1] 2.0  NA  NA  NA 1.0 0.5 2.5  NA  NA  NA  NA  NA 1.0