Learn R Programming

quickOutlier (version 0.1.5)

detect_ts_outliers: Detect Anomalies in Time Series using STL Decomposition

Description

Performs a seasonal-trend decomposition using Loess (STL) to separate the time series into three components: Trend, Seasonality, and Remainder (Noise). Outliers are then detected in the Remainder component using the Interquartile Range (IQR) method.

Usage

detect_ts_outliers(data, frequency = 12)

Value

A data frame containing:

Original

The original values.

Trend

The extracted long-term trend component.

Seasonal

The extracted seasonal component.

Remainder

The remaining noise after removing trend and seasonality.

Is_Outlier

Logical flag. TRUE if the Remainder value is an outlier based on IQR (3 * IQR).

Arguments

data

A numeric vector representing the time series values.

frequency

Integer. The number of observations per cycle (e.g., 12 for monthly data, 7 for daily data).

Details

This method is superior to simple thresholding for time series because it accounts for:

  • Seasonality: Repeating patterns (e.g., higher sales in December).

  • Trend: Long-term increase or decrease.

An observation is flagged as an outlier only if it is unusual after accounting for these normal temporal patterns.

Examples

Run this code
# Example: Synthetic monthly data with a clear anomaly
sales <- c(sin(seq(1, 20, 0.5)) * 10 + 50) # Normal pattern
sales[10] <- 200 # Inject outlier
result <- detect_ts_outliers(sales, frequency = 12)
subset(result, Is_Outlier == TRUE)

Run the code above in your browser using DataLab