R/summarize_panel.R

Defines functions summarize_panel

Documented in summarize_panel

#' Summarize a two-wave panel with overlap
#'
#' Internal helper to compute wave sizes, means, variances, and stayer
#' covariance/variances from individual-level data.
#'
#' @param data Data frame containing at least id, wave, and metric columns.
#' @param wave_0 Value in `wave_col` for the first wave.
#' @param wave_1 Value in `wave_col` for the second wave.
#' @param id_col Column name for the employee identifier.
#' @param wave_col Column name for the wave identifier.
#' @param metric_col Column name for the metric.
#'
#' @return A list with N0, N1, nS, ybar0, ybar1, V0_ind, V1_ind,
#'   C01_ind, V0S_ind, V1S_ind.
#' @keywords internal
summarize_panel <- function(data, wave_0, wave_1,
                            id_col, wave_col, metric_col) {
  id    <- data[[id_col]]
  wave  <- data[[wave_col]]
  y     <- data[[metric_col]]
  
  if (anyNA(id) || anyNA(wave) || anyNA(y)) {
    stop("v0.1 does not handle missing values in id, wave, or metric; please clean NAs upstream.")
  }
  
  w0_idx <- wave == wave_0
  w1_idx <- wave == wave_1
  if (!any(w0_idx) || !any(w1_idx)) {
    stop("Both waves must have at least one observation.")
  }
  
  if (any(duplicated(paste(id, wave, sep = "___")))) {
    stop("Duplicate id-wave combinations detected; aggregate upstream for v0.1.")
  }
  
  ids0 <- id[w0_idx]
  ids1 <- id[w1_idx]
  
  N0 <- length(ids0)
  N1 <- length(ids1)
  
  y0 <- y[w0_idx]
  y1 <- y[w1_idx]
  
  ybar0 <- base::mean(y0)
  ybar1 <- base::mean(y1)
  
  V0_ind <- stats::var(y0)
  V1_ind <- stats::var(y1)
  
  stayer_ids <- base::intersect(ids0, ids1)
  nS <- length(stayer_ids)
  
  if (nS > 0L) {
    match0 <- base::match(stayer_ids, ids0)
    match1 <- base::match(stayer_ids, ids1)
    y0S <- y0[match0]
    y1S <- y1[match1]
    C01_ind <- stats::cov(y0S, y1S)
    V0S_ind <- stats::var(y0S)
    V1S_ind <- stats::var(y1S)
  } else {
    C01_ind <- NA_real_
    V0S_ind <- NA_real_
    V1S_ind <- NA_real_
  }
  
  list(
    N0 = N0,
    N1 = N1,
    nS = nS,
    ybar0 = ybar0,
    ybar1 = ybar1,
    V0_ind = V0_ind,
    V1_ind = V1_ind,
    C01_ind = C01_ind,
    V0S_ind = V0S_ind,
    V1S_ind = V1S_ind
  )
}

Try the wavecov package in your browser

Any scripts or data that you put into this service are public.

wavecov documentation built on Nov. 3, 2026, 5:07 p.m.