Skip to contents

Applies anomaly detection to a ts object using either direct or decomposition-based methods. Internally uses a customized version of anomalize logic with robust thresholding.

Usage

anomaly(
  ts,
  max.anom = 100,
  scale = 1.5,
  method = "iqr",
  decomp = NULL,
  tzero = 0
)

Arguments

ts

A ts object. Input time series data.

max.anom

An integer (default: 100). Maximum number of anomalies allowed.

scale

A numeric (default: 1.5). Controls the IQR scaling factor. Corresponds to standard 1.5×IQR rule. Internally converted to alpha = 0.15 / scale for compatibility with anomalize2().

method

A character. Outlier detection method passed to anomalize2. One of "iqr" or "gesd".

decomp

A character or NULL. Optional decomposition method for time series. One of "stl", "twitter", etc., or NULL for no decomposition. When specified, decomposes the time series using anomalize's time_decompose().

tzero

A numeric (default: 0). Ignored. Included only for compatibility with other pipeline functions.

Value

A tibble with the original time series and added columns:

observed

Original input values.

<observed>_l1, <observed>_l2

Lower and upper bounds for anomaly detection.

anomaly

Anomaly flag: 1 for anomaly, 0 otherwise.

(Optional)

Additional decomposition columns: trend, season, remainder if decomp is used.

Details

This function builds on anomalize by replacing the default anomaly detection with customized functions iqr2 and gesd2, which return binary anomaly indicators (0 or 1). Pipe operators are not used. The scale parameter is internally translated into a significance level using the formula: alpha = 0.15 / scale.

If decomp is specified, the function decomposes the time series into trend, seasonal, and remainder components, estimates the trend period automatically via ACF using decomp_freq_trend, and applies anomaly detection to the remainder component only. The final result is then recomposed using time_recompose().

Examples

if (FALSE) { # \dontrun{
x <- ts(c(rnorm(100), 10, 15), frequency = 1)
anomaly(x, method = "iqr")
anomaly(x, method = "gesd", scale = 2)
} # }