roll_MAD: Roll MAD

View source: R/MazamaRollUtils.R

roll_MADR Documentation

Roll MAD

Description

Apply a moving-window Median Absolute Deviation function to a numeric vector.

Usage

roll_MAD(
  x,
  width = 1L,
  by = 1L,
  align = c("center", "left", "right"),
  na.rm = FALSE,
  min_valid = NULL
)

Arguments

x

Numeric vector.

width

Integer width of the rolling window.

by

Integer shift by which the window is moved each iteration.

align

Character position of the return value within the window. One of: "left" | "center" | "right".

na.rm

Logical specifying whether NA values should be removed before the calculations within each window.

min_valid

Integer minimum number of non-NA values that must fall within a window for that window to return a non-NA result. Supplying min_valid implies NA-tolerant counting within each window (as if na.rm = TRUE), regardless of na.rm. The default, NULL, applies no minimum.

Details

For every index in the incoming vector x, a value is returned that is the Median Absolute Deviation (MAD) of all values in x that fall within a window of width width.

The value returned is the unscaled MAD – the median of the absolute deviations from the window median, with no consistency constant applied. This is equivalent to stats::mad(window, constant = 1). Note that stats::mad() uses constant = 1.4826 by default, so values from roll_MAD() are smaller than the stats::mad() default by that factor.

The align parameter determines the alignment of the return value within the window. Thus:

  • ⁠align = "left" [*------]⁠ will cause the returned vector to have width - 1 NA values at the right end.

  • ⁠align = "center" [---*---]⁠ will cause the returned vector to have NA values at either end as needed for centered alignment.

  • ⁠align = "right" [------*]⁠ will cause the returned vector to have width - 1 NA values at the left end.

For large vectors, the by parameter can be used to force the window to jump ahead by indices for the next calculation. Indices that are skipped over will be assigned NA values so that the return vector still has the same length as the incoming vector. This can dramatically speed up calculations for high resolution time series data.

Value

Numeric vector of the same length as x.

Examples

# Wikipedia example
x <- c(0, 0, 0, 1, 1, 2, 2, 4, 6, 9, 0, 0, 0)
roll_MAD(x, 3)
roll_MAD(x, 5)
roll_MAD(x, 7)


MazamaRollUtils documentation built on Sept. 1, 2026, 5:09 p.m.