Apply a moving-window Hampel function to a numeric vector.
roll_hampel(
x,
width = 1L,
by = 1L,
align = c("center", "left", "right"),
na.rm = FALSE,
min_valid = NULL
)Numeric vector.
Integer width of the rolling window.
Integer shift by which the window is moved each iteration.
Character position of the return value within the window. One of:
"left" | "center" | "right".
Logical specifying whether NA values should be removed
before the calculations within each window.
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.
Numeric vector of the same length as x.
The Hampel filter is a robust outlier detector using Median Absolute Deviation (MAD).
For every index in the incoming vector x, a value is returned that
is the Hampel function of all values in x that fall within a window of width
width. The score at each index compares the value at that index
(x[i]) with the median and MAD of its window: abs(x[i] - median) / (1.4826 * MAD). Larger scores indicate values less consistent with their
neighborhood. With align = "center" the tested value sits at the middle
of its window; with align = "left" or "right" it sits at the window
edge. Outlier detection (see findOutliers()) is normally done with the
default align = "center".
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.
x <- c(0, 0, 0, 1, 1, 2, 2, 4, 6, 9, 0, 0, 0)
roll_hampel(x, 3)
#> [1] NA 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
#> [8] 0.0000000 0.0000000 0.6744908 0.0000000 0.0000000 NA