Skip to contents

Replaces each selected field with a rolling weighted average taken within each panel ID, ordered by time.

Usage

panel_smooth(
  data,
  vars,
  window = 3,
  weights = c("equal", "half", "decay"),
  align = c("center", "left", "right"),
  time = "TAX_YEAR",
  id = "EIN2",
  verbose = TRUE
)

Arguments

data

A panel data frame.

vars

Numeric fields to smooth.

window

Rolling-window width: an odd integer for align = "center", any positive integer otherwise.

weights

"equal", "half", or "decay".

align

"center" (default, row-based centred window), "right" (trailing calendar-year window, no future values), or "left" (forward-looking calendar-year window). See Window alignment.

time

Panel-time column.

id

Panel-ID column.

verbose

Print progress.

Value

Input rows in original order with selected fields smoothed.

Window alignment

  • "center" (default) averages the window rows centred on the focal row. Positions are counted by row, not calendar year, so a filing gap is bridged; at the ends of a series the fixed-width window slides inward, and IDs with fewer rows than window use all their rows. window must be odd.

  • "right" is a trailing (backward-looking) window: for a row in year t it uses only rows whose time falls in t - (window - 1) through t. Years are counted on the calendar, so a missing filing year simply leaves a hole in the window – it is never bridged by reaching further back – and no value later than t is ever used. Early rows use whatever of the window is observed.

  • "left" is the forward-looking mirror: years t through t + (window - 1).

For "right" and "left", window may be any positive integer and time must be numeric (or coercible to numeric, such as "2021").

Weights

Weights are assigned to the window's slots and then renormalized over the values actually present.

  • "equal": every slot counts the same.

  • "half": the focal year gets 0.5; the other window - 1 slots share the other 0.5 equally.

  • "decay": 0.5^distance, where distance is in rows for "center" and in calendar years (t - year for "right", year - t for "left") otherwise.

Missing values (NA/NaN) are dropped from each window and the remaining weights renormalized, so a missing focal value is filled from its neighbours; a window with nothing observed returns NA.

Examples

df <- data.frame(EIN2 = "A", TAX_YEAR = c(2018, 2019, 2021, 2022),
                 revenue = c(10, 20, 30, 40))
# centred (row-based)
panel_smooth(df, "revenue", verbose = FALSE)$revenue
#> [1] 20 20 30 30
# trailing 3-year window; 2020 is missing, so 2021 uses 2019 and 2021 only
panel_smooth(df, "revenue", align = "right", verbose = FALSE)$revenue
#> [1] 10 15 25 35