Cross-sectional averages by time (with optional leave-one-out)
Source:R/utils_avg.R
cross_sectional_avg.RdComputes cross-sectional averages (CSAs) of specified variables for each time period, optionally in a leave-one-out (LOO) fashion per observation. Supports unbalanced panels and observation weights.
Usage
cross_sectional_avg(
data,
id = NULL,
time = NULL,
vars,
leave_out = FALSE,
weights = NULL,
suffix = "csa",
return_mode = c("attach", "time"),
na.rm = TRUE
)Arguments
- data
A
data.frameorplm::pdata.frame.- id, time
Character scalar names of unit and time columns when
datais a plaindata.frame. Ifdatais apdata.frame, these are inferred from its index and can be omitted.- vars
Character vector of column names to average cross-sectionally.
- leave_out
Logical; if
TRUE, computes LOO means for each row: \(\bar{x}_{-i,t} = (\sum_{j \neq i} w_{jt} x_{jt}) / (\sum_{j \neq i} w_{jt})\). IfFALSE, computes standard time means: \(\bar{x}_{t} = (\sum_j w_{jt} x_{jt}) / (\sum_j w_{jt})\).- weights
Optional. Either:
a numeric vector of length
nrow(data), orthe name of a column in
datawith nonnegative weights.
If
NULL, uses equal weights (1 for observed values).- suffix
Character suffix to append to CSA columns (default
"csa").- return_mode
One of
"attach"or"time"."attach"returns the originaldatawith CSA columns added."time"returns a unique-time table[time, csa_*].
- na.rm
Logical; if
TRUE, excludesNAs from sums and denominators. IfFALSE, anyNAin a time slice yieldsNAfor that time's CSA for that variable.
Value
A data.frame:
If
return_mode="attach": original data + CSA columns namedpaste0(suffix, "_", vars).If
return_mode="time": unique time rows with CSA columns.
Details
This is a standalone data utility. It does not configure the averages used by
csdm(); use csdm_csa() for that purpose. Model fitting constructs averages
from the evaluated model terms and its documented source sample, which can
differ from averages of raw data columns produced here.
Efficiently computes, for each v in vars and time t,
$$\bar v_t = \frac{\sum_i w_{it}\, 1_{\{v_{it}\text{ finite}\}}\, v_{it}}
{\sum_i w_{it}\, 1_{\{v_{it}\text{ finite}\}}}$$
For leave_out=TRUE, each row's CSA excludes its own contribution; if the
denominator becomes \(\le 0\) (e.g., only one finite observation at that time),
the LOO mean is set to NA for that row/variable.