augment_rolling: Add rolling aggregation columns to a data frame

View source: R/augment_rolling.R

augment_rollingR Documentation

Add rolling aggregation columns to a data frame

Description

Pipe-friendly companion to augment_trends() for rolling and year-to-date aggregations: 12-month accumulated totals, compounded rates of change, rolling volatility, and so on. Columns are prefixed roll_ rather than trend_, because these are aggregations of the series and not estimates of its trend.

Usage

augment_rolling(
  data,
  date_col = "date",
  value_col = "value",
  group_cols = NULL,
  stats = "sum",
  window = NULL,
  frequency = NULL,
  align = "right",
  percent = FALSE,
  na_rm = FALSE,
  suffix = NULL,
  .quiet = FALSE
)

Arguments

data

A data.frame, tibble, or data.table containing the time series data.

date_col

Name of the date column. Defaults to "date". Must be of class Date.

value_col

Name of the value column(s). Defaults to "value". Must be numeric. A character vector of length > 1 is accepted; aggregations are computed for each column and named ⁠roll_{stat}_{window}_{col}⁠.

group_cols

Optional grouping variables for multiple time series. Can be a character vector of column names.

stats

Character vector of rolling statistics. Options: "sum" (rolling total of flows), "chain" (compound accumulation of rates, prod(1 + r) - 1), "change" (change of a level over window periods, x[t] / x[t - window] - 1), "mean", "sd", "min", "max". Default is "sum".

window

Window length in periods, or the lag for "change". If NULL, defaults to the detected frequency (12 for monthly, 4 for quarterly). A numeric vector adds one column per window value. Alternatively, the string "ytd" computes an expanding year-to-date accumulation that resets each January (or Q1), and "all" an expanding accumulation from the first observation. Numeric and character windows cannot be mixed in one call, and "change" needs a numeric window.

frequency

The frequency of the series. Supports values from 1 (annual) to 365 (daily). Auto-detected if not specified.

align

Alignment of the window relative to the output position: "right" (default), "center", or "left". Ignored by "change" and by the expanding windows "ytd" and "all". An even window has no exact centre; see roll_series() for how each statistic handles that.

percent

Only used by stats = "chain" and stats = "change". For "chain", if FALSE (default), rates are assumed to be decimals (0.005 for 0.5%). If TRUE, rates are assumed to be percentages (0.5 for 0.5%) and the result is returned in percent. For "change", TRUE returns the change in percent instead of as a decimal.

na_rm

If TRUE, missing values are ignored within each window. The default FALSE propagates NA, so an incomplete window yields NA. A window holding no observed values yields NA either way, as does a window holding one value for "sd". For even centered means, observed weights are renormalized under na_rm = TRUE; boundary padding is kept. "change" ignores it: a missing value at either end yields NA.

suffix

Optional suffix appended to the generated column names.

.quiet

If TRUE, suppress informational messages.

Details

Use "sum" for flows measured in levels and "chain" for series that are already rates of change. Summing monthly inflation rates approximates the 12-month accumulation but is not equal to it; "chain" compounds them correctly. "change" turns a level into its rate of change, matching each date with the one window periods earlier rather than the row window positions above. See roll_series() for the underlying computation.

"mean" overlaps with the simple moving average available through augment_trends(methods = "ma"). The two differ in defaults rather than in substance: rolling aggregations default to right alignment, while the moving average trend defaults to centred alignment. Given the same window and alignment they agree, including the 2xN correction for even centred windows.

Rows whose value is NA are kept in place, so window positions stay aligned with the calendar; na_rm then decides whether such a window yields NA or is computed from the observations that are present. Unlike augment_trends(), which rejects gaps inside the observed range, a rolling window has well-defined local behaviour for a gap, so these functions accept one. A period that is absent from the data altogether cannot be positioned, so it raises an error rather than shifting later observations — add the missing rows with an NA value first.

Value

A tibble with the original data plus rolling columns named ⁠roll_{stat}_{window}⁠ (e.g. roll_sum_12, roll_chain_ytd, roll_change_12), with ⁠_{suffix}⁠ appended when suffix is supplied. Rows come back in the order they were supplied in.

See Also

roll_series() for the time series interface, augment_trends() for trend estimation.

Examples

# 12-month accumulated vehicle production
vehicles |> augment_rolling(value_col = "production", window = 12)

# Several windows at once
vehicles |>
  tail(60) |>
  augment_rolling(value_col = "production", window = c(3, 6, 12))

# Rolling mean and volatility side by side
ibcbr |>
  augment_rolling(value_col = "index", stats = c("mean", "sd"), window = 12)

# Year-to-date accumulation, resetting each January
vehicles |> augment_rolling(value_col = "production", window = "ytd")

# 12-month change of an index, in percent
ibcbr |>
  augment_rolling(value_col = "index", stats = "change", percent = TRUE)

# Grouped series
retail_volume |>
  augment_rolling(group_cols = "name_series", window = 12)


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