Computes rolling linear regression slope (first derivative) for a numeric
response variable y within a moving window.
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
xfor rolling local calculations.- align
Specifies the window alignment of
spanas "center" (the default), "left", or "right". Where "left" is forward looking, and "right" is backward looking by the windowspanfrom 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 localysamples are valid.TRUEwill return the rolling slopes where the local targetysample is valid.
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.
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