View source: R/decompose_series.R
| decompose_series | R Documentation |
Pipe-friendly function that decomposes a time series into its trend, seasonal, and remainder components, adding them as columns to the input data frame.
decompose_series(
data,
date_col = "date",
value_col = "value",
group_cols = NULL,
methods = "stl",
trend = "linear",
transform = "none",
frequency = NULL,
seasadj = FALSE,
params = list(),
.quiet = FALSE
)
data |
A |
date_col |
Name of the date column. Defaults to |
value_col |
Name of the value column. Defaults to |
group_cols |
Optional grouping variables for multiple time series. A character vector of column names. When provided, decomposition is applied independently to each group. |
methods |
Decomposition method(s). One or more of
|
trend |
For |
transform |
Transformation applied to the series before decomposition.
One of |
frequency |
The frequency of the series. Must be greater than 1;
|
seasadj |
If |
params |
Optional list of method-specific parameters for fine control. Every parameter has a default, so this argument is only needed for non-standard use cases. For STL (
For regression (
classic, bsm, and seats take no |
.quiet |
If |
All methods require seasonal data (frequency > 1). For non-seasonal
(annual) series, use augment_trends() to extract a trend component only.
Uses stats::stl() (Seasonal-Trend decomposition via Loess). The seasonal
component is estimated with a loess smoother, the trend with an adaptive
moving average, and the remainder is the residual. The defaults
(s.window = "periodic", robust = FALSE) assume a stable seasonal pattern.
Fits a joint OLS model:
y_t = f(t) + s(t) + \epsilon_t
where f(t) is a polynomial in time and s(t) is captured by
period dummy variables (month or quarter indicators). The components are
isolated via stats::predict(type = "terms"):
Trend: constant + polynomial terms (captures the long-run level and direction).
Seasonal: period dummy terms, centred to mean zero over the sample.
Remainder: residuals from the full model.
By default, orthogonal polynomials (poly_raw = FALSE) are used for numerical
stability, which matters most for trend = "cubic".
Uses stats::decompose(). The trend is a centred moving average of order
equal to the frequency; the seasonal component is the average detrended value
for each period; the remainder is the residual. Simple and fast, but the
other methods handle evolving seasonality and the endpoints better.
Uses stats::StructTS(type = "BSM"), a state-space model with stochastic
level, slope, and seasonal components estimated by maximum likelihood and
extracted with the Kalman smoother (stats::tsSmooth()). Unlike the
moving-average methods it produces trend and seasonal estimates for every
observation, including the endpoints, and lets both components evolve over
time. Fitting relies on numerical optimisation and can occasionally fail to
converge on short or irregular series.
Uses the seasonal package, which wraps the U.S. Census Bureau's
X-13ARIMA-SEATS program. seas() is run with its automatic defaults (model
selection, log/level transformation, outlier detection, and calendar
adjustment), and the SEATS trend-cycle (s12) and seasonally adjusted series
(s11) are mapped to an additive trend/seasonal/remainder, whichever
transformation X-13 picked internally. Because X-13 picks that
transformation itself, seats is best used with the default
transform = "none"; an outer log transform is redundant.
When the seasonal amplitude grows with the level of the series (a
multiplicative pattern, common in economic data), set transform = "log".
The series is log-transformed, decomposed additively, and the components are
exponentiated back. Every method takes this same path, which requires
strictly positive values.
A tibble with the original columns plus, for each requested method,
three new columns (and a fourth when seasadj = TRUE):
trend_{method}: the estimated trend component.
seasonal_{method}: the estimated seasonal component.
remainder_{method}: what remains after removing trend and seasonal.
seasadj_{method}: the seasonally adjusted series (only if seasadj = TRUE).
With transform = "none" the components should add back up to the series
(value = trend + seasonal + remainder); with transform = "log" they
should multiply back to it (value = trend * seasonal * remainder).
For "classic" the trend (and hence remainder) is NA for the first and
last frequency / 2 observations (the centred moving average has no
boundary support).
Output rows come back in the order they were supplied in.
# STL decomposition (default settings work well for most economic series)
gdp_construction |>
decompose_series(value_col = "index")
# STL with robust fitting (useful when the series has outliers)
gdp_construction |>
decompose_series(
value_col = "index",
params = list(robust = TRUE)
)
# STL with evolving seasonality (s.window controls how fast it can change)
gdp_construction |>
decompose_series(
value_col = "index",
params = list(s.window = 13)
)
# Regression with cubic trend
gdp_construction |>
decompose_series(
value_col = "index",
methods = "regression",
trend = "cubic"
)
# Classical decomposition via moving averages (boundary trend is NA)
gdp_construction |>
decompose_series(
value_col = "index",
methods = "classic"
)
# Basic Structural Model (state-space, components for every observation)
gdp_construction |>
decompose_series(
value_col = "index",
methods = "bsm"
)
# X-13ARIMA-SEATS (requires the 'seasonal' package)
if (requireNamespace("seasonal", quietly = TRUE)) {
gdp_construction |>
decompose_series(
value_col = "index",
methods = "seats"
)
}
# Multiplicative decomposition via log transform (works for any method)
oil_derivatives |>
decompose_series(
value_col = "production",
transform = "log"
)
# Several methods at once for side-by-side comparison
gdp_construction |>
decompose_series(
value_col = "index",
methods = c("stl", "classic")
)
# Also return the seasonally adjusted series
gdp_construction |>
decompose_series(
value_col = "index",
seasadj = TRUE
)
# Grouped decomposition: one decomposition per electricity sector
electricity |>
decompose_series(
group_cols = "name_series"
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.