R/multi.R

Defines functions plot.regsensitivity_multi print.summary.regsensitivity_multi summary.regsensitivity_multi as.data.frame.regsensitivity_multi print.regsensitivity_multi regsen_multi

Documented in as.data.frame.regsensitivity_multi plot.regsensitivity_multi print.regsensitivity_multi print.summary.regsensitivity_multi regsen_multi summary.regsensitivity_multi

## multi.R --- run the same sensitivity analysis across several treatments.

#' Sensitivity analysis for several treatments at once
#'
#' Runs [regsen_breakdown()] (or [regsen_bounds()]) once per candidate
#' treatment and collects the breakdown points into one table. This is the
#' applied question "which of my regressors would survive an unobservable,
#' and which would not?", answered in a single call.
#'
#' Each treatment is analysed in the *same* model: the variable of interest
#' moves to the front of the formula and every other right-hand-side term
#' stays a control, including the other candidate treatments. That is
#' deliberate -- dropping the others would change the specification and the
#' breakdown points would no longer be comparable across rows.
#'
#' @param formula A model formula. Its right-hand side must contain every
#'   name in `treatments`. Which term appears first does not matter here,
#'   since each treatment is promoted in turn.
#' @param data A data frame.
#' @param treatments Character vector of variables to treat as the
#'   treatment in turn.
#' @param compare Passed to the underlying analysis. A variable currently
#'   acting as the treatment is removed from `compare` for that row, since
#'   a variable cannot calibrate against itself.
#' @param fun The analysis to run: [regsen_breakdown()] (default) or
#'   [regsen_bounds()].
#' @param ... Passed to `fun`, e.g. `cbar`, `analysis`, `beta`.
#' @param ncores Number of cores to spread the treatments over. `NULL`
#'   (default) uses the session setting of [regsen_cores()]; `"auto"` uses
#'   all but two of the machine's cores. Each treatment's analysis then
#'   runs serially inside, so cores are not oversubscribed.
#'
#' @return A `data.frame` of class `regsensitivity_multi`, one row per
#'   treatment, with columns `treatment`, `estimate` (the medium-regression
#'   coefficient), `breakdown`, and `n`. Rows where the analysis failed
#'   carry `NA` and an `error` column explaining why, rather than aborting
#'   the whole sweep.
#'
#' @examples
#' data(bfg2020)
#' w1 <- c("log_area_2010", "lat", "lon")
#' regsen_multi(
#'     avgrep2000to2016 ~ tye_tfe890_500kNI_100_l6 + log_area_2010 + lat + lon,
#'     data = bfg2020,
#'     treatments = c("tye_tfe890_500kNI_100_l6", "lat"),
#'     compare = w1, cbar = 1
#' )
#' @export
regsen_multi <- function(formula, data, treatments,
                         compare = NULL, fun = regsen_breakdown, ...,
                         ncores = NULL) {
    stopifnot(is.data.frame(data))
    if (!is.character(treatments) || length(treatments) == 0) {
        stop("`treatments` must be a non-empty character vector.",
             call. = FALSE)
    }
    fun <- match.fun(fun)
    ncores <- resolve_ncores(ncores)
    # Force every argument the worker closure will touch. A socket worker
    # receives an unevaluated promise as a promise and evaluates it there,
    # where the caller's variables do not exist.
    force(compare)

    rhs <- attr(stats::terms(formula), "term.labels")
    lhs <- all.vars(formula)[1]
    missing_terms <- setdiff(treatments, rhs)
    if (length(missing_terms)) {
        stop("not on the right-hand side of `formula`: ",
             paste(missing_terms, collapse = ", "), call. = FALSE)
    }

    # Treatments run across the cores; the analysis of each runs serially
    # inside, when `fun` knows how to be told so.
    inner <- if ("ncores" %in% names(formals(fun))) list(ncores = 1L) else list()
    dots <- list(...)

    one <- function(i) {
        tr <- treatments[i]
        # Promote this treatment; everything else stays a control so the
        # specification is identical across rows.
        f_tr <- stats::reformulate(c(tr, setdiff(rhs, tr)), response = lhs)
        cmp <- if (is.null(compare)) NULL else setdiff(compare, tr)

        res <- tryCatch(
            do.call(fun, c(list(f_tr, data, compare = cmp), dots, inner)),
            error = function(e) e
        )
        if (inherits(res, "error")) {
            return(data.frame(treatment = tr, estimate = NA_real_,
                              breakdown = NA_real_, n = NA_integer_,
                              error = conditionMessage(res),
                              stringsAsFactors = FALSE))
        }

        bp <- res$breakdown
        if (is.null(bp) || length(bp) != 1) {
            bp <- if (!is.null(res$results$breakdown)) {
                res$results$breakdown[1]
            } else {
                NA_real_
            }
        }
        data.frame(
            treatment = tr,
            estimate  = if (!is.null(res$dgp$beta_med)) res$dgp$beta_med
                        else NA_real_,
            breakdown = abs(bp),
            n         = res$n,
            error     = NA_character_,
            stringsAsFactors = FALSE
        )
    }
    rows <- par_lapply(length(treatments), one, ncores)
    # A worker that died (rather than an analysis that errored, which
    # `one` already catches) is reported the same way, in its row.
    rows <- lapply(seq_along(rows), function(i) {
        r <- rows[[i]]
        if (!inherits(r, "try-error")) return(r)
        data.frame(treatment = treatments[i], estimate = NA_real_,
                   breakdown = NA_real_, n = NA_integer_,
                   error = conditionMessage(attr(r, "condition")),
                   stringsAsFactors = FALSE)
    })

    out <- do.call(rbind, rows)
    rownames(out) <- NULL
    # Drop the error column when nothing failed, so the common case is a
    # clean four-column table.
    if (all(is.na(out$error))) out$error <- NULL
    analysis <- tryCatch(
        switch(match_analysis(if (is.null(dots$analysis)) "dmp" else dots$analysis),
               dmp = "DMP (2026)", oster = "Oster (2019)"),
        error = function(e) NA_character_
    )
    structure(out, class = c("regsensitivity_multi", "data.frame"),
              call = match.call(), analysis = analysis)
}

#' @rdname regsen_multi
#' @export
print.regsensitivity_multi <- function(x, ...) {
    cat("\nSensitivity across treatments\n")
    cat(strrep("-", 60), "\n", sep = "")
    df <- as.data.frame(x)
    num <- vapply(df, is.numeric, logical(1))
    df[num] <- lapply(df[num], function(v) formatC(v, format = "fg", digits = 4))
    print(df, row.names = FALSE)
    if (!is.null(x$error) && any(!is.na(x$error))) {
        cat("\n(", sum(!is.na(x$error)), " treatment(s) failed; see the ",
            "`error` column.)\n", sep = "")
    }
    invisible(x)
}

#' @rdname regsen_multi
#' @param row.names,optional Ignored, present for S3 compatibility with
#'   [base::as.data.frame()].
#' @export
as.data.frame.regsensitivity_multi <- function(x, row.names = NULL,
                                               optional = FALSE, ...) {
    # The table alone: the call and analysis label describe how it was made,
    # and two runs that differ only in, say, `ncores` give the same table.
    attr(x, "call") <- NULL
    attr(x, "analysis") <- NULL
    class(x) <- "data.frame"
    x
}

#' @rdname regsen_multi
#' @param object A `regsensitivity_multi` object.
#' @return `summary()` returns an object of class
#'   `summary.regsensitivity_multi`: the treatments ordered from most to
#'   least fragile, with the count of those whose breakdown point is below
#'   1, the benchmark at which the omitted variable is no more important
#'   than the comparison controls.
#' @export
summary.regsensitivity_multi <- function(object, ...) {
    df <- as.data.frame(object)
    df <- df[order(df$breakdown, na.last = TRUE), , drop = FALSE]
    df$rank <- seq_len(nrow(df))
    df$rank[is.na(df$breakdown)] <- NA_integer_
    rownames(df) <- NULL
    bp <- df$breakdown[!is.na(df$breakdown)]
    structure(
        list(
            call = attr(object, "call"),
            analysis = attr(object, "analysis"),
            table = df,
            n_treatments = nrow(df),
            n_failed = sum(is.na(df$breakdown)),
            n_below_one = sum(bp < 1),
            range = if (length(bp)) range(bp) else c(NA_real_, NA_real_)
        ),
        class = "summary.regsensitivity_multi"
    )
}

#' @rdname regsen_multi
#' @export
print.summary.regsensitivity_multi <- function(x, ...) {
    cat("\nSensitivity across treatments")
    if (!is.null(x$analysis) && !is.na(x$analysis)) {
        cat(" [", x$analysis, "]", sep = "")
    }
    cat("\n", strrep("-", 60), "\n", sep = "")
    if (!is.null(x$call)) {
        cat("Call:\n  ", paste(deparse(x$call, width.cutoff = 68),
                               collapse = "\n  "), "\n\n", sep = "")
    }
    cat(sprintf("  %-34s %d\n", "Treatments:", x$n_treatments))
    if (x$n_failed > 0) {
        cat(sprintf("  %-34s %d (see the `error` column)\n", "Failed:",
                    x$n_failed))
    }
    cat(sprintf("  %-34s %d\n", "Breakdown point below 1:", x$n_below_one))
    if (!anyNA(x$range)) {
        cat(sprintf("  %-34s [%s, %s]\n", "Breakdown range:",
                    format_bp(x$range[1]), format_bp(x$range[2])))
    }
    cat("\nMost fragile first:\n")
    df <- x$table
    num <- vapply(df, is.double, logical(1))
    df[num] <- lapply(df[num], function(v) formatC(v, format = "fg", digits = 4))
    print(df, row.names = FALSE)
    invisible(x)
}

#' @rdname regsen_multi
#' @param x A `regsensitivity_multi` object, or for the `print()` method of
#'   its summary, a `summary.regsensitivity_multi` object.
#' @param base_size Base font size, passed to [theme_regsen()].
#' @export
plot.regsensitivity_multi <- function(x, base_size = 11, ...) {
    df <- as.data.frame(x)
    df <- df[is.finite(df$breakdown), , drop = FALSE]
    if (nrow(df) == 0) {
        stop("no finite breakdown points to plot.", call. = FALSE)
    }
    # Most fragile at the top: the ordering a reader wants first.
    df$treatment <- factor(df$treatment,
                           levels = df$treatment[order(df$breakdown)])

    ggplot2::ggplot(df, ggplot2::aes(x = .data$breakdown, y = .data$treatment)) +
        ggplot2::geom_segment(
            ggplot2::aes(x = 0, xend = .data$breakdown,
                         y = .data$treatment, yend = .data$treatment),
            colour = "grey70", linewidth = 0.4) +
        ggplot2::geom_point(size = 2.2, colour = okabe_ito[1]) +
        ggplot2::labs(x = "Breakdown point", y = NULL) +
        theme_regsen(base_size = base_size, grid = "x")
}

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.