detrend_series: Detrend a time series

View source: R/detrend_series.R

detrend_seriesR Documentation

Detrend a time series

Description

Pipe-friendly convenience wrapper around augment_trends() focused on a single task: removing the trend from a time series. It adds a ⁠detrend_{method}⁠ column holding the detrended series (the deviation from trend, often called the cycle in economics) and, optionally, the underlying trend itself.

For econometric filters such as "hp" (the default), "bk", "cf", and "hamilton", the detrended series is the business-cycle component those filters were designed to isolate (e.g. the output gap).

Usage

detrend_series(
  data,
  date_col = "date",
  value_col = "value",
  group_cols = NULL,
  methods = "hp",
  transform = "none",
  frequency = NULL,
  components = FALSE,
  window = NULL,
  smoothing = NULL,
  band = NULL,
  align = NULL,
  params = list(),
  .quiet = FALSE
)

Arguments

data

A data.frame, tibble, data.table, or tsibble containing the time series data. Tsibble support requires the optional tsibble package.

date_col

Name of the date column. Defaults to "date". Must be of class Date for data frames. For tsibbles, defaults to the index and must name that index when supplied.

value_col

Name of the value column(s). Defaults to "value". Must be numeric. A character vector of length > 1 is accepted; each column is detrended separately and the results are named ⁠detrend_{method}_{col}⁠ (e.g. detrend_hp_consumption).

group_cols

Optional grouping variables for multiple time series. Can be a character vector of column names. For tsibbles, defaults to the key and must match it when supplied.

methods

Character vector of trend methods used for detrending. Any method supported by augment_trends() is accepted. Default is "hp" (Hodrick-Prescott filter with frequency-appropriate smoothing). When several methods are supplied, each one contributes its own ⁠detrend_{method}⁠ column so the detrended series can be compared side by side.

transform

Transformation applied before detrending. One of:

  • "none" (default): the trend is fitted to the raw series and detrend = value - trend, in the units of the series.

  • "log": the trend is fitted to the log series and detrend = log(value) - log(trend), the log deviation from trend. Multiplied by 100, this is approximately the percentage deviation from trend (the convention for output gaps). Requires strictly positive values. The ⁠trend_{method}⁠ columns (when components = TRUE) are reported back in the units of the series.

frequency

The frequency of the series. Supports values from 1 (annual) to 365 (daily). Auto-detected for data frames; a tsibble's yearmonth or yearquarter index supplies 12 or 4. A Date index uses the usual detection. Other tsibble index classes are not supported.

components

If FALSE (default), only the detrended ⁠detrend_{method}⁠ column is added. If TRUE, the fitted ⁠trend_{method}⁠ column is also kept.

window

Unified window/period parameter for moving average methods; see augment_trends(). For "ma", "median", and "henderson", a numeric vector is accepted (e.g. c(6, 12)), which adds one detrended column per window value (detrend_ma_6, detrend_ma_12, ...).

smoothing

Unified smoothing parameter for smoothing methods (hp, loess, spline, ewma, kernel, kalman). For hp: use large values (1600+) or small values (0-1) that get converted. For EWMA: specifies the alpha parameter (0-1) for traditional exponential smoothing. Cannot be used simultaneously with window for EWMA method. For kernel: multiplier of optimal bandwidth (1.0 = optimal, <1 = less smooth, >1 = more smooth). For kalman: a finite, positive ratio of measurement to process noise (higher = more smoothing). An explicit noise variance in params determines the other variance from this ratio. If both variances are supplied, they take precedence over smoothing. Without a ratio, unspecified measurement and process variances default to 0.1 and 0.01 times the series variance. For others: typically 0-1 range.

band

Unified band parameter for bandpass filters (bk, cf). Provide as c(low, high): the shortest and longest cycle to remove, in periods of the series (months for monthly data). Both values must be positive. Defaults to cycles of 1.5 to 8 years: c(6, 32) for quarterly data, c(18, 96) for monthly, and c(2, 8) for annual.

align

Unified alignment parameter for moving average methods (ma, wma, triangular, gaussian). Valid values: "center" (default, uses surrounding values), "right" (causal, uses past values only), "left" (anti-causal, uses future values only). Note: triangular only supports "center" and "right". If NULL, uses "center" as default.

params

Optional list of method-specific parameters for fine control.

.quiet

If TRUE, suppress informational messages.

Details

detrend_series() is a thin wrapper: it calls augment_trends() with the requested methods and subtracts each fitted trend from the series (on the log scale when transform = "log"). All trend-fitting behaviour, validation, grouping, and the unified parameters (window, smoothing, band, align, params) are inherited unchanged from augment_trends(). See its documentation for method internals and parameter details. Tsibble input supports the same Date, yearmonth, and yearquarter indices as augment_trends().

Detrending does not remove seasonality: the detrended series of a raw seasonal series still contains the seasonal swings, and seasonality can leak into the cycle estimated by filters such as HP. For seasonal data, seasonally adjust first and detrend the adjusted series (see Examples), or use decompose_series() for a full trend/seasonal/remainder split.

Value

A tibble with the original columns plus, for each requested method, a ⁠detrend_{method}⁠ column holding the detrended series. When components = TRUE, the ⁠trend_{method}⁠ column is kept as well.

Each detrended column mirrors the name of the trend column it derives from: window vectors yield detrend_ma_6, detrend_ma_12, and a trend column renamed to avoid a naming conflict yields a matching detrended name.

With transform = "none" the trend and the detrended series should add back up to the original (value = trend + detrend); with transform = "log" the relation is value = trend * exp(detrend). Methods with boundary effects (e.g. "bk", "hamilton") produce NA trend values at the affected observations, and the detrended series is NA there too.

Output rows come back in the order they were supplied in. A tsibble input returns a tsibble with its index class and key preserved.

See Also

augment_trends() for the underlying trend extraction and the full set of methods; deseason_series() to remove seasonality; decompose_series() for a full decomposition.

Examples

# HP-filter detrending (the default): adds a detrend_hp column
gdp_construction |>
  detrend_series(value_col = "index")

# Log deviation from trend (x 100 ~ percentage gap, the output-gap convention)
gdp_construction |>
  detrend_series(value_col = "index", transform = "log")

# Keep the fitted trend alongside the detrended series
gdp_construction |>
  detrend_series(value_col = "index", components = TRUE)

# Compare detrending methods side by side
gdp_construction |>
  detrend_series(value_col = "index", methods = c("hp", "stl", "loess"))

# Seasonal data: deseason first, then detrend the adjusted series
gdp_construction |>
  deseason_series(value_col = "index") |>
  detrend_series(value_col = "seasadj_stl")

# Grouped detrending: one trend per electricity sector
electricity |>
  detrend_series(group_cols = "name_series")


trendseries documentation built on Oct. 1, 2026, 5:10 p.m.