R/dgp.R

Defines functions sumstats_table whitener get_dgp drop_aliased project_residuals subset_dgp_inputs build_dgp_inputs

## dgp.R --- compute the summary statistics that every sensitivity analysis
## consumes.
##
## All identified-set and breakdown-point calculations in this package depend
## only on Var(Y, X, W1) after partialling out W0. We compute that variance
## matrix once and cache the derived quantities used downstream.

# Internal: build a model frame from a formula spec and split controls into
# `w1` (the comparison controls) and `w0` (the "other" controls which we
# partial out before computing the variance matrix).
#
# The argument names mirror the Stata `compare()`/`nocompare()` options:
#  - compare:   names of variables to USE as the comparison set
#  - nocompare: names of variables to EXCLUDE from the comparison set
#               (i.e. everything else becomes the comparison set)
#
# Factor variables are expanded via model.matrix and any aliased columns
# (perfectly collinear after partialling out the intercept) are dropped.
build_dgp_inputs <- function(formula, data, compare = NULL, nocompare = NULL,
                              subset = NULL) {
    if (!inherits(formula, "formula")) {
        stop("`formula` must be a formula object (e.g. y ~ x + w).",
             call. = FALSE)
    }
    if (!is.data.frame(data)) {
        stop("`data` must be a data.frame.", call. = FALSE)
    }
    # Row positions in the data as handed in, carried through subsetting and
    # na.omit so that a caller can line another column of `data` up with the
    # rows the analysis actually used (regsen_boot() does this for clusters).
    orig_rows <- seq_len(nrow(data))
    if (!is.null(subset)) {
        # A logical subset with NAs would select rows of NA, which na.omit
        # then drops silently; an NA in the row bookkeeping would later
        # misalign a cluster column. Treat NA as FALSE, as subset() does.
        # A logical subset of the wrong length used to be recycled by `[`
        # and then reported as "got 1 observation", which pointed nowhere
        # near the mistake.
        if (is.logical(subset) && length(subset) != nrow(data)) {
            stop("`subset` is a logical vector of length ", length(subset),
                 ", but `data` has ", nrow(data), " rows.", call. = FALSE)
        }
        # Negative indices (rows to drop) are fine; numbers past the last
        # row would select rows of NA that na.omit then drops silently.
        if (is.numeric(subset) && any(abs(subset) > nrow(data), na.rm = TRUE)) {
            stop("`subset` holds row numbers beyond the ", nrow(data),
                 " rows of `data`.", call. = FALSE)
        }
        if (is.logical(subset)) subset <- which(subset)
        data <- data[subset, , drop = FALSE]
        orig_rows <- orig_rows[subset]
    }
    if (nrow(data) < 10) {
        stop("Need at least 10 complete observations; got ", nrow(data), ".",
             call. = FALSE)
    }
    mf <- stats::model.frame(formula, data = data, na.action = stats::na.omit)
    if (nrow(mf) < 10) {
        stop("Fewer than 10 complete observations remain after na.omit; got ",
             nrow(mf), ". Consider imputing or removing rows with NAs.",
             call. = FALSE)
    }
    y <- stats::model.response(mf)
    # A one-sided formula has no response, and a cbind() response is a
    # matrix: the first used to run on y = NULL, the second on a matrix
    # read as one long vector.
    if (is.null(y) || !is.null(dim(y)) || !(is.numeric(y) || is.logical(y))) {
        stop("`formula` needs a single numeric outcome on its left-hand ",
             "side (e.g. y ~ x + w).", call. = FALSE)
    }
    tt <- stats::terms(mf)
    # x is the first non-response term; remaining terms are controls.
    rhs <- attr(tt, "term.labels")
    if (length(rhs) < 1) {
        stop("formula must include at least an independent variable",
             call. = FALSE)
    }
    xname <- rhs[1]
    control_names <- rhs[-1]

    # Determine compare / nocompare partition.
    if (!is.null(compare) && !is.null(nocompare)) {
        stop("specify at most one of `compare` and `nocompare`", call. = FALSE)
    }
    # A name that is not a control term used to be dropped without a word,
    # so a typo in `compare` silently changed which covariates calibrate
    # the analysis. Naming the treatment is the same mistake: a variable
    # cannot be its own yardstick.
    for (arg in c("compare", "nocompare")) {
        nms <- get(arg)
        if (is.null(nms)) next
        if (!is.character(nms)) {
            stop("`", arg, "` must be a character vector of control names.",
                 call. = FALSE)
        }
        unknown <- setdiff(nms, control_names)
        if (length(unknown)) {
            stop("`", arg, "` names ", if (length(unknown) == 1) "a term "
                 else "terms ", "not among the controls on the right-hand ",
                 "side of `formula`: ", paste(unknown, collapse = ", "),
                 if (xname %in% unknown) paste0(
                     ". (", xname, " is the treatment, the first ",
                     "right-hand-side term, and cannot calibrate itself.)")
                 else ".", call. = FALSE)
        }
    }
    if (is.null(compare) && is.null(nocompare)) {
        w1_names <- control_names
        w0_names <- character(0)
    } else if (!is.null(compare)) {
        w1_names <- intersect(control_names, compare)
        w0_names <- setdiff(control_names, w1_names)
    } else {
        w0_names <- intersect(control_names, nocompare)
        w1_names <- setdiff(control_names, w0_names)
    }

    expand <- function(nms, data, drop_first = TRUE) {
        if (length(nms) == 0) {
            return(matrix(numeric(0), nrow = nrow(data), ncol = 0))
        }
        f <- stats::as.formula(paste("~", paste(nms, collapse = " + ")))
        mm <- stats::model.matrix(f, data = data)
        if (drop_first && "(Intercept)" %in% colnames(mm)) {
            mm <- mm[, setdiff(colnames(mm), "(Intercept)"), drop = FALSE]
        }
        mm
    }

    # Use the same row-wise complete-cases as mf, robust to any kind of
    # row labels (integer vs character vs subset-preserved).
    keep_rows <- match(rownames(mf), rownames(data))
    use_data <- data[keep_rows, , drop = FALSE]
    x <- expand(xname, use_data)
    if (ncol(x) != 1) {
        stop("independent variable must be numeric/scalar", call. = FALSE)
    }
    x <- x[, 1]
    w1 <- expand(w1_names, use_data)
    w0 <- expand(w0_names, use_data)

    # na.omit drops NA and NaN but keeps Inf, which used to surface as
    # "NA/NaN/Inf in foreign function call" from deep inside qr().
    bad <- c(if (any(!is.finite(y))) all.vars(formula)[1],
             if (any(!is.finite(x))) xname,
             colnames(w1)[colSums(!is.finite(w1)) > 0],
             colnames(w0)[colSums(!is.finite(w0)) > 0])
    if (length(bad)) {
        stop("Infinite values in ", paste0("`", bad, "`", collapse = ", "),
             ". Remove or recode those rows before the analysis.",
             call. = FALSE)
    }

    list(
        y = y, x = x, w1 = w1, w0 = w0,
        y_name = all.vars(formula)[1],
        x_name = xname,
        compare_names = colnames(w1),
        control_names = c(colnames(w1), colnames(w0)),
        rows = orig_rows[keep_rows],
        n = length(y)
    )
}

# Take a row subset (or resample) of already-built dgp inputs.
#
# `rows` may repeat indices, which is what a bootstrap resample needs. The
# model matrices are reused rather than rebuilt, so a factor level missing
# from the resample leaves an all-zero column behind rather than dropping
# one: `get_dgp()` removes aliased comparison columns, and the QR it runs
# on the control block handles a rank deficiency there.
subset_dgp_inputs <- function(inputs, rows) {
    inputs$y  <- inputs$y[rows]
    inputs$x  <- inputs$x[rows]
    inputs$w1 <- inputs$w1[rows, , drop = FALSE]
    inputs$w0 <- inputs$w0[rows, , drop = FALSE]
    inputs$n  <- length(rows)
    inputs
}

# Residualize a numeric matrix on `w0` (after adding an intercept).
#
# When `w0` is empty we still demean each column (the Stata workflow always
# includes a constant in W0).
project_residuals <- function(mat, w0) {
    if (is.null(dim(mat))) {
        mat <- matrix(mat, ncol = 1)
    }
    if (ncol(w0) == 0) {
        # Just demean (equivalent to projecting onto a constant).
        mu <- colMeans(mat)
        return(sweep(mat, 2, mu, FUN = "-"))
    }
    # Add intercept, solve in one go for all columns.
    W <- cbind(1, w0)
    qrW <- qr(W)
    fit <- qr.fitted(qrW, mat)
    mat - fit
}

# Drop the columns of the residualized comparison block that carry no
# information about the omitted variable's yardstick:
#
#   - columns collinear with W0, whose variance vanishes once W0 is
#     partialled out. This is judged relative to the column's variance
#     before partialling, so a covariate measured in small units is not
#     mistaken for a constant (an absolute 1e-12 cut-off used to do that);
#   - columns collinear with the other comparison columns, found as a rank
#     deficiency by pivoted QR. Var(W1) is singular in that case and the
#     Cholesky inverse the analysis rests on does not exist.
#
# Stata's regsensitivity drops both kinds the same way.
drop_aliased <- function(w_res, w_orig) {
    if (ncol(w_res) == 0) return(w_res)
    v_res  <- apply(w_res,  2, stats::var)
    v_orig <- apply(w_orig, 2, stats::var)
    keep <- v_res > 1e-10 * pmax(v_orig, .Machine$double.eps)
    w_res <- w_res[, keep, drop = FALSE]
    if (ncol(w_res) > 1) {
        q <- qr(w_res)
        if (q$rank < ncol(w_res)) {
            w_res <- w_res[, sort(q$pivot[seq_len(q$rank)]), drop = FALSE]
        }
    }
    w_res
}

# Compute Var(Y, X, W1) and all the derived quantities used by the analyses.
#
# Mirrors `get_dgp` in the Stata source. The returned object is an S3 list
# of class `regsen_dgp` and holds the same fields as the Mata struct dgp.
#
# Fields:
#   var_y, var_x        : variances of (residualized) Y, X
#   var_w               : variance matrix of (residualized) W1
#   k0, k1, k2          : DMP scalars (k0 = Var(MX|W1), etc.)
#   wxwx, wywy, wxwy    : inner products  cov_wx' wt cov_wx, etc.
#   covwx_norm_sq       : Var(X) - k0
#   beta_short          : OLS coefficient of Y on X alone
#   beta_med            : OLS coefficient of Y on X + W1
#   gamma_med, pi_med   : Y- and X- partial coefficients on W1 (unweighted)
#   gamma_med_norm_sq   : ||gamma_med||^2 under wt
#   r_short, r_med      : R^2 of the short and medium regressions
#   var_x_resid         : equals k0; kept under the Oster name
#   c_change_basis      : 2x2 matrix used inside the DIRECT optimization
#
# `inputs` is the list returned by `build_dgp_inputs()`.
get_dgp <- function(inputs) {
    y <- inputs$y; x <- inputs$x; w1 <- inputs$w1; w0 <- inputs$w0

    # Partial out W0 (and a constant) from (Y, X, W1).
    yxw <- cbind(y, x, w1)
    yxw_r <- project_residuals(yxw, w0)
    yr <- yxw_r[, 1]
    xr <- yxw_r[, 2]
    if (ncol(w1) > 0) {
        w1r <- yxw_r[, -(1:2), drop = FALSE]
    } else {
        w1r <- matrix(numeric(0), nrow = length(yr), ncol = 0)
    }
    w1r <- drop_aliased(w1r, w1)

    # Variance matrix V = Var((Y, X, W1)) after residualizing.
    data_block <- cbind(yr, xr, w1r)
    V <- stats::var(data_block)

    var_y <- V[1, 1]
    var_x <- V[2, 2]
    if (ncol(w1r) == 0) {
        # No comparison controls. Many quantities simplify; we still allow
        # the analysis to run but a number of the sensitivity parameters
        # become meaningless. We populate the struct with sensible defaults.
        var_w <- matrix(0, 0, 0)
        covwx <- numeric(0)
        covwy <- numeric(0)
        zx <- numeric(0); zy <- numeric(0)
        wxwx <- 0; wywy <- 0; wxwy <- 0
    } else {
        var_w <- V[-(1:2), -(1:2), drop = FALSE]
        covwx <- V[-(1:2), 2]
        covwy <- V[-(1:2), 1]
        # Every quadratic form below is u' Var(W1)^{-1} v. Whitening u and v
        # once turns each into a crossprod() of two vectors, so the inverse
        # is never formed.
        whiten <- whitener(var_w)
        zx <- whiten(covwx)
        zy <- whiten(covwy)
        wxwx <- sum(zx^2)
        wywy <- sum(zy^2)
        wxwy <- as.numeric(crossprod(zx, zy))
    }
    covxy <- V[1, 2]

    k0 <- var_x - wxwx
    k1 <- covxy - wxwy
    k2 <- var_y - wywy

    # With no variation left in the treatment, beta_med = k1 / k0 divides
    # rounding error by rounding error: a constant treatment used to come
    # back with a coefficient of 1e15 and a breakdown point that looked
    # like any other. Judge "no variation" relative to the variable's
    # variance before partialling, by the same cut-off drop_aliased() uses.
    novar <- function(v_after, v_before) {
        !is.finite(v_after) || v_after <= 1e-10 * max(v_before, .Machine$double.eps)
    }
    if (novar(var_y, stats::var(inputs$y))) {
        stop("The outcome `", inputs$y_name, "` has no variation once the ",
             "controls outside the comparison set are partialled out: it is ",
             "constant, or a linear combination of those controls.",
             call. = FALSE)
    }
    if (novar(k0, stats::var(inputs$x))) {
        stop("The treatment `", inputs$x_name, "` has no variation once the ",
             "controls are partialled out: it is constant, or a linear ",
             "combination of the controls. Its coefficient is not identified.",
             call. = FALSE)
    }
    covwx_norm_sq <- var_x - k0

    beta_short <- covxy / var_x
    beta_med <- k1 / k0
    var_x_resid <- k0

    if (ncol(w1r) == 0) {
        gamma_med <- numeric(0)
        pi_med <- numeric(0)
        gamma_med_norm_sq <- 0
        gamma_wx <- 0
    } else {
        gamma_med <- covwy - beta_med * covwx
        pi_med <- covwx
        # Whitening is linear, so gamma_med whitens to zy - beta_med * zx.
        zg <- zy - beta_med * zx
        gamma_med_norm_sq <- sum(zg^2)
        gamma_wx <- as.numeric(crossprod(zg, zx))
    }

    r_short <- beta_short^2 * var_x / var_y
    r_med <- (beta_med^2 * var_x + gamma_med_norm_sq +
              2 * beta_med * gamma_wx) / var_y

    # Change-of-basis matrix used in the DIRECT optimization (DMP, ry<inf, c>0).
    wy_orthogonal_norm <- sqrt(max(wywy * wxwx - wxwy^2, 0))
    wxnorm <- sqrt(max(wxwx, 0))
    c_change_basis <- matrix(c(
        if (wxnorm > 0) 1 / wxnorm else 0,
        0,
        if (wy_orthogonal_norm > 0 && wxnorm > 0) -wxwy / wy_orthogonal_norm / wxnorm else 0,
        if (wy_orthogonal_norm > 0) wxnorm / wy_orthogonal_norm else 0
    ), nrow = 2, byrow = FALSE)

    structure(
        list(
            var_y = var_y, var_x = var_x, var_w = var_w,
            k0 = k0, k1 = k1, k2 = k2,
            wxwx = wxwx, wywy = wywy, wxwy = wxwy,
            covwx_norm_sq = covwx_norm_sq,
            beta_short = beta_short, beta_med = beta_med,
            gamma_med = gamma_med, pi_med = pi_med,
            gamma_med_norm_sq = gamma_med_norm_sq,
            r_short = r_short, r_med = r_med,
            var_x_resid = var_x_resid,
            c_change_basis = c_change_basis,
            n_compare = ncol(w1r),
            n = length(yr)
        ),
        class = "regsen_dgp"
    )
}

# A function taking v to L^{-1} v, where L L' = V, so that the whitened
# vectors' crossprod() is u' V^{-1} v. V is a variance matrix, hence
# symmetric and positive semi-definite: the Cholesky factor is the cheap
# route, and the symmetric eigendecomposition the fallback when V is
# singular to working precision. drop_aliased() removes exact collinearity
# first, so the fallback is rare; it discards the directions with no
# variance, giving the Moore-Penrose form rather than a ridge-perturbed
# inverse whose entries grow without bound as V approaches singularity.
whitener <- function(V) {
    ch <- tryCatch(chol(V), error = function(e) NULL)
    if (!is.null(ch)) {
        return(function(v) backsolve(ch, v, transpose = TRUE))
    }
    e <- eigen(V, symmetric = TRUE)
    tol <- max(dim(V)) * max(e$values, 0) * .Machine$double.eps
    keep <- e$values > tol
    scale <- t(e$vectors[, keep, drop = FALSE]) / sqrt(e$values[keep])
    function(v) drop(scale %*% v)
}

# A small helper used by display code.
sumstats_table <- function(dgp) {
    data.frame(
        statistic = c("Beta (short)", "Beta (medium)",
                      "R2 (short)", "R2 (medium)",
                      "Var(Y)", "Var(X)", "Var(X_Residual)"),
        value = c(dgp$beta_short, dgp$beta_med,
                  dgp$r_short, dgp$r_med,
                  dgp$var_y, dgp$var_x, dgp$var_x_resid),
        stringsAsFactors = FALSE
    )
}

Try the regsensitivity package in your browser

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

regsensitivity documentation built on Nov. 23, 2026, 9:08 a.m.