collapse_to_period: Collapse multiple rows sharing a period into one

View source: R/aggregate_period.R

collapse_to_periodR Documentation

Collapse multiple rows sharing a period into one

Description

Snaps each row's ds to the start of its period (per date_agg) and combines rows that land on the same period (and, if group_col is supplied, the same group) – e.g. case data split by district/sex/age with many rows per Year+Quarter.

Usage

collapse_to_period(
  df,
  date_agg = "day",
  fun = c("sum", "mean", "median", "none"),
  group_col = NULL
)

Arguments

df

A data frame with ds (date-like) and y (numeric) columns.

date_agg

Aggregation frequency: one of "hour", "day", "week", "month", "quarter", "year".

fun

How to combine rows sharing a period: "sum" (the default, for counts), "mean"/"median" (for rates/indices, where summing across strata would be meaningless), or "none" (return df unchanged).

group_col

Optional character scalar; rows only collapse together if they share both a period and this column's value.

Value

A tibble with one row per period (and group, if group_col is supplied), columns ds/y(/group_col).

Examples

df <- data.frame(ds = as.Date(c("2024-01-01", "2024-01-02")), y = c(3, 5))
collapse_to_period(df, date_agg = "month")

forecastsuite documentation built on Oct. 18, 2026, 5:08 p.m.