Nothing
#' Decompose the change in a group gap between consecutive occasions
#'
#' @description
#' For each pair of consecutive scheduled occasions \eqn{(t-1, t)} and each
#' focal group \eqn{g}, splits the observed decision-rate gap
#' \eqn{\Delta_t = \pi_g(t) - \pi_r(t)} into the prior gap carried forward,
#' a recovery contribution, a retention contribution and two terms that link
#' the units with decisions at both occasions to everyone with a decision at
#' each occasion. The split is an accounting identity: the components add
#' up to the observed change exactly.
#'
#' @param object An `aibias` object from [AIBias::aib_build()].
#' @param ref_group Character. Reference group. If NULL, uses the first level.
#' @param min_cell Integer. A step is flagged as sparse when any of the four
#' prior-state cells (focal/reference by prior decision 0/1) among paired
#' units has fewer than `min_cell` units. Default 10.
#' @param verbose Logical. Print a short summary.
#'
#' @details
#' Let the *paired* units at step \eqn{t} be those with a recorded decision
#' at both \eqn{t-1} and \eqn{t}. Within group \eqn{h} among paired units,
#' let \eqn{q_h} be the share with a favorable decision at \eqn{t-1}, and
#' let \eqn{p_{01,h}} (recovery) and \eqn{p_{11,h}} (retention) be the
#' shares favorable at \eqn{t} given an unfavorable or favorable decision at
#' \eqn{t-1}. Write \eqn{\Delta} for focal minus reference, a bar for the
#' average of the two groups, and \eqn{s_h = p_{11,h} - p_{01,h}}. The
#' current gap among paired units is exactly
#' \deqn{\Delta^P_t = \bar s\,\Delta^P_{t-1} + (1-\bar q)\,\Delta p_{01}
#' + \bar q\,\Delta p_{11},}
#' where \eqn{\Delta^P_{t-1} = \Delta q} is the prior gap among the same
#' units (Kitagawa, 1955, symmetric weights). Writing
#' \eqn{S_t = \Delta_t - \Delta^P_t} and
#' \eqn{S_{t-1} = \Delta_{t-1} - \Delta^P_{t-1}} for the differences between
#' the full observed gap and the paired gap at each occasion gives
#' \deqn{\Delta_t - \Delta_{t-1} = (\bar s - 1)\Delta^P_{t-1}
#' + (1-\bar q)\Delta p_{01} + \bar q\,\Delta p_{11} + (S_t - S_{t-1}).}
#'
#' The identity holds for any recorded data. It does not assume that the
#' previous decision causes the current one, that the process is Markov, or
#' that missing decisions are missing at random. Those assumptions matter
#' only when the components are read as features of a population process.
#'
#' Pairs always use consecutive scheduled occasions (integer time index).
#' A unit that misses occasion \eqn{t-1} contributes to the full gap at
#' \eqn{t} but not to the paired quantities. A data row with a missing
#' decision counts as present but unscored.
#'
#' Each unit must belong to one group throughout; the function stops
#' otherwise.
#'
#' **Empty cells.** When a prior-state cell is empty, the step is marked
#' `supported = FALSE` and only the components that do not need the missing
#' rate are returned:
#' - always estimable (given both groups have recorded decisions):
#' `gap_prev`, `gap_curr`, `change`, `gap_pair_prev`, `gap_pair_curr`,
#' `sample_prev`, `sample_curr`, `sample_change`;
#' - `recovery` needs paired units with an unfavorable prior decision in both
#' groups (`n0_g`, `n0_ref` > 0);
#' - `retention` needs paired units with a favorable prior decision in both
#' groups (`n1_g`, `n1_ref` > 0);
#' - `carry` and `decay` need all four cells.
#'
#' Components that cannot be estimated are `NA`, and so is `recon_error`,
#' because the remaining components no longer add up to the change.
#'
#' @return The `aibias` object with `$decomposition` populated, a list with
#' - `steps`: one row per focal group and step, with counts, rates,
#' gaps and components (see below)
#' - `totals`: components summed over all steps, per focal group
#' - `ref_group`, `min_cell`
#'
#' Key columns of `steps`: `gap_prev`, `gap_curr` (full observed gaps),
#' `change` (their difference), `gap_pair_prev`, `gap_pair_curr`,
#' `carry` (\eqn{\bar s\,\Delta^P_{t-1}}), `decay`
#' (\eqn{(\bar s-1)\Delta^P_{t-1}}), `recovery`, `retention`,
#' `sample_prev` (\eqn{S_{t-1}}), `sample_curr` (\eqn{S_t}),
#' `sample_change` (\eqn{S_t - S_{t-1}}), `recon_error` (numerical
#' check, zero up to rounding), the counts `n_units_*` (units in the
#' panel), `n_present_*` (units with a data row), `n_obs_*` (units with a
#' recorded decision), `n_pair_*` (paired units), `n0_*` and `n1_*`
#' (paired units with an unfavorable or favorable prior decision), and the
#' flags `supported` and `sparse`. Suffix `_g` is the focal group and
#' `_ref` the reference group.
#'
#' @references
#' Kitagawa, E. M. (1955). Components of a difference between two rates.
#' *Journal of the American Statistical Association*, 50(272), 1168--1194.
#'
#' @examples
#' data(lending_panel)
#' obj <- aib_build(lending_panel, "applicant_id", "year", "race", "approved",
#' verbose = FALSE)
#' obj <- aib_decompose(obj, ref_group = "White")
#' obj$decomposition$steps[, c("group", "time_from", "time_to", "change",
#' "decay", "recovery", "retention",
#' "sample_change")]
#'
#' @export
aib_decompose <- function(object,
ref_group = NULL,
min_cell = 10,
verbose = TRUE) {
.check_aibias(object)
.check_fixed_group(object, "aib_decompose()")
ref_group <- .resolve_ref_group(object, ref_group)
if (object$meta$n_times < 2)
abort("At least two occasions are needed for `aib_decompose()`.")
dm <- .decision_matrix(object)
focal <- setdiff(as.character(object$meta$groups), ref_group)
steps <- .decompose_core(dm$Y, dm$R, dm$G, ref_group, focal, min_cell)
labs <- as.character(object$meta$raw_times)
steps$time_from <- labs[steps$time - 1L]
steps$time_to <- labs[steps$time]
steps <- steps[, c("group", "ref_group", "time", "time_from", "time_to",
setdiff(names(steps),
c("group", "ref_group", "time",
"time_from", "time_to")))]
steps <- as_tibble(steps)
totals <- .decompose_totals(steps)
object$decomposition <- list(
steps = steps,
totals = totals,
ref_group = ref_group,
min_cell = min_cell
)
if (verbose) {
cli_h2("Gap decomposition (ref: {ref_group})")
for (g in focal) {
tg <- totals[totals$group == g, ]
cli_li(paste0(
"Group ", g, ": gap ", sprintf("%+.3f", tg$gap_first), " -> ",
sprintf("%+.3f", tg$gap_last), " (change ", sprintf("%+.3f", tg$change),
"); decay ", sprintf("%+.3f", tg$decay),
", recovery ", sprintf("%+.3f", tg$recovery),
", retention ", sprintf("%+.3f", tg$retention),
", sample ", sprintf("%+.3f", tg$sample_change)))
if (tg$n_unsupported > 0)
cli_alert_warning(
"Group {g}: {tg$n_unsupported} step(s) with an empty prior-state cell.")
if (tg$n_sparse > 0)
cli_alert_warning(
"Group {g}: {tg$n_sparse} step(s) with a prior-state cell below {min_cell}.")
}
}
invisible(object)
}
# ---- Internal: per-group counts for all steps ------------------------------
.group_step_stats <- function(Yh, Rh) {
nT <- ncol(Yh)
Op <- !is.na(Yh)
Yz <- Yh
Yz[!Op] <- 0L
n_present <- colSums(Rh)
n_obs <- colSums(Op)
rate_full <- colSums(Yz) / n_obs
prv <- seq_len(nT - 1L)
cur <- prv + 1L
B <- Op[, prv, drop = FALSE] & Op[, cur, drop = FALSE]
Yp <- Yz[, prv, drop = FALSE] == 1L
Yc <- Yz[, cur, drop = FALSE] == 1L
P1 <- B & Yp
P0 <- B & !Yp
n_pair <- colSums(B)
n1 <- colSums(P1)
n0 <- colSums(P0)
c11 <- colSums(P1 & Yc)
c01 <- colSums(P0 & Yc)
list(
n_units = nrow(Yh),
n_present = n_present,
n_obs = n_obs,
rate_full = rate_full,
n_pair = n_pair,
n0 = n0,
n1 = n1,
q = n1 / n_pair,
p01 = c01 / n0,
p11 = c11 / n1,
pair_curr = (c01 + c11) / n_pair
)
}
.nan_to_na <- function(x) { x[is.nan(x)] <- NA_real_; x }
# Core decomposition on the unit-by-occasion layout. Used by aib_decompose()
# and by aib_bootstrap(), so both compute exactly the same quantities.
.decompose_core <- function(Y, R, G, ref_group, focal, min_cell = 10) {
nT <- ncol(Y)
prv <- seq_len(nT - 1L)
cur <- prv + 1L
sr <- .group_step_stats(Y[G == ref_group, , drop = FALSE],
R[G == ref_group, , drop = FALSE])
out <- lapply(focal, function(g) {
sg <- .group_step_stats(Y[G == g, , drop = FALSE],
R[G == g, , drop = FALSE])
gap_prev <- sg$rate_full[prv] - sr$rate_full[prv]
gap_curr <- sg$rate_full[cur] - sr$rate_full[cur]
gap_pair_prev <- sg$q - sr$q
gap_pair_curr <- sg$pair_curr - sr$pair_curr
q_bar <- (sg$q + sr$q) / 2
s_g <- sg$p11 - sg$p01
s_r <- sr$p11 - sr$p01
s_bar <- (s_g + s_r) / 2
carry <- s_bar * gap_pair_prev
recovery <- (1 - q_bar) * (sg$p01 - sr$p01)
retention <- q_bar * (sg$p11 - sr$p11)
decay <- carry - gap_pair_prev
sample_prev <- gap_prev - gap_pair_prev
sample_curr <- gap_curr - gap_pair_curr
sample_change <- sample_curr - sample_prev
change <- gap_curr - gap_prev
min_n <- pmin(sg$n0, sg$n1, sr$n0, sr$n1)
supported <- min_n > 0
sparse <- supported & min_n < min_cell
data.frame(
group = g,
ref_group = ref_group,
time = cur,
gap_prev = .nan_to_na(gap_prev),
gap_curr = .nan_to_na(gap_curr),
change = .nan_to_na(change),
gap_pair_prev = .nan_to_na(gap_pair_prev),
gap_pair_curr = .nan_to_na(gap_pair_curr),
carry = .nan_to_na(carry),
decay = .nan_to_na(decay),
recovery = .nan_to_na(recovery),
retention = .nan_to_na(retention),
sample_prev = .nan_to_na(sample_prev),
sample_curr = .nan_to_na(sample_curr),
sample_change = .nan_to_na(sample_change),
recon_error = .nan_to_na(change -
(decay + recovery + retention + sample_change)),
q_g = .nan_to_na(sg$q), q_ref = .nan_to_na(sr$q),
p01_g = .nan_to_na(sg$p01), p01_ref = .nan_to_na(sr$p01),
p11_g = .nan_to_na(sg$p11), p11_ref = .nan_to_na(sr$p11),
n_units_g = sg$n_units, n_units_ref = sr$n_units,
n_present_prev_g = sg$n_present[prv], n_present_prev_ref = sr$n_present[prv],
n_present_curr_g = sg$n_present[cur], n_present_curr_ref = sr$n_present[cur],
n_obs_prev_g = sg$n_obs[prv], n_obs_prev_ref = sr$n_obs[prv],
n_obs_curr_g = sg$n_obs[cur], n_obs_curr_ref = sr$n_obs[cur],
n_pair_g = sg$n_pair, n_pair_ref = sr$n_pair,
n0_g = sg$n0, n1_g = sg$n1, n0_ref = sr$n0, n1_ref = sr$n1,
min_cell_n = min_n,
supported = supported,
sparse = sparse,
stringsAsFactors = FALSE
)
})
do.call(rbind, out)
}
.decompose_totals <- function(steps) {
groups <- unique(steps$group)
out <- lapply(groups, function(g) {
s <- steps[steps$group == g, , drop = FALSE]
tibble(
group = g,
gap_first = s$gap_prev[1],
gap_last = s$gap_curr[nrow(s)],
change = sum(s$change),
decay = sum(s$decay),
recovery = sum(s$recovery),
retention = sum(s$retention),
sample_change = sum(s$sample_change),
n_steps = nrow(s),
n_unsupported = sum(!s$supported),
n_sparse = sum(s$sparse)
)
})
bind_rows(out)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.