R/robust.R

Defines functions robust_low_sentence robust_note_sentences robust_weights lmrob_wald_tests robust_performance apa_performance.rlm apa_performance.lmrob apa_parameters.rlm

Documented in apa_parameters.rlm apa_performance.lmrob apa_performance.rlm

# Robust regression tables ----

#' @details
#' For robust regression models (`MASS::rlm` and `robustbase::lmrob`),
#' coefficients are tested with *t* tests, as in linear regression, but
#' cases with large residuals get less weight. Standardized coefficients are
#' not shown by default, because standardizing with the ordinary standard
#' deviations does not match a robust fit. [apa_note()] names the estimator
#' and its weight function (e.g., MM-estimation with bisquare weights), says
#' how the standard errors were computed, and gives *N* and the number of
#' cases whose weights are below .10, which have almost no influence on the
#' estimates. For `rlm`, the *p*-values are computed by the parameters
#' package, because MASS gives none.
#' @references
#' Huber, P. J. (1964). Robust estimation of a location parameter. *The
#' Annals of Mathematical Statistics, 35*(1), 73--101.
#' \doi{10.1214/aoms/1177703732}
#'
#' Renaud, O., & Victoria-Feser, M.-P. (2010). A robust coefficient of
#' determination for regression. *Journal of Statistical Planning and
#' Inference, 140*(7), 1852--1862. \doi{10.1016/j.jspi.2010.01.008}
#'
#' Yohai, V. J. (1987). High breakdown-point and high efficiency robust
#' estimates for regression. *The Annals of Statistics, 15*(2), 642--656.
#' \doi{10.1214/aos/1176350366}
#' @export
#' @rdname apa_parameters
#' @examples
#' \donttest{
#' if (requireNamespace("robustbase", quietly = TRUE) &&
#'     requireNamespace("carData", quietly = TRUE)) {
#'   # Reported weight by measured weight; one measured weight is a data
#'   # entry error (weight and height swapped)
#'   d <- carData::Davis
#'   robustbase::lmrob(repwt ~ weight * sex, data = d) |>
#'     apa_parameters()
#' }
#' }
apa_parameters.rlm <- function(
  fit,
  predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  ...
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL
  if (inherits(fit, "rlm") && isFALSE(fit$converged)) {
    cli::cli_warn("The robust regression did not converge, so its estimates may not be trustworthy.")
  }

  d_b <- parameters::model_parameters(fit, ...) |>
    tibble::as_tibble()
  d_b$Parameter <- pretty_parameter_names(fit, d_b$Parameter)

  format_apa_parameters(
    d_b,
    predictor_parameters = predictor_parameters,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats,
    t_with_df = t_with_df,
    note = list(
      model_sentences = robust_note_sentences(fit),
      robust_low = sum(robust_weights(fit) < .1, na.rm = TRUE)
    )
  )
}

#' @export
#' @rdname apa_parameters
apa_parameters.lmrob <- apa_parameters.rlm

# Fit statistics and comparisons ----

#' @details
#' For robust regression models fit with `robustbase::lmrob`, `R2` is the
#' robust *R*^2^ of Renaud and Victoria-Feser (2010), and `Sigma_robust` is
#' the robust residual scale. For models fit with `MASS::rlm`, which have no
#' *R*^2^, the default metric is the robust residual scale. Nested `lmrob`
#' models are compared with robust Wald tests in
#' [apa_performance_comparison()], and `rlm` models without tests.
#' @export
#' @rdname apa_performance
apa_performance.lmrob <- function(
  fit,
  metrics = c("R2", "Sigma_robust"),
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- c("R2", "R2_adjusted", "Sigma_robust")
  }
  format_performance(robust_performance(fit), metrics, column_formats)
}

#' @export
#' @rdname apa_performance
apa_performance.rlm <- function(
  fit,
  metrics = "Sigma_robust",
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- "Sigma_robust"
  }
  format_performance(robust_performance(fit), metrics, column_formats)
}

#' Fit statistics of a robust regression model
#' @keywords internal
#' @noRd
robust_performance <- function(fit) {
  if (inherits(fit, "lmrob")) {
    s <- summary(fit)
    return(tibble::tibble(
      R2_robust = s$r.squared,
      R2_adjusted = s$adj.r.squared,
      Sigma_robust = fit$scale
    ))
  }
  tibble::tibble(Sigma_robust = fit$s)
}

#' Robust Wald tests of nested lmrob models, each against the one before it
#' @returns tibble with `Chi2`, `df`, and `p` (missing for the first model)
#' @keywords internal
#' @noRd
lmrob_wald_tests <- function(models) {
  tests <- purrr::map(seq_along(models), \(i) {
    if (i == 1) {
      return(tibble::tibble(Chi2 = NA_real_, df = NA_real_, p = NA_real_))
    }
    # anova.lmrob() wants the larger model first
    pair <- models[c(i, i - 1)]
    if (length(stats::coef(pair[[2]])) > length(stats::coef(pair[[1]]))) {
      pair <- rev(pair)
    }
    a <- as.data.frame(stats::anova(pair[[1]], pair[[2]]))
    tibble::tibble(Chi2 = a$Test.Stat[2], df = abs(a$Df[2]), p = a[["Pr(>chisq)"]][2])
  })
  dplyr::bind_rows(tests)
}

# Note sentences ----

#' Robustness weights of the cases (1 for full weight, 0 for none)
#' @keywords internal
#' @noRd
robust_weights <- function(fit) {
  if (inherits(fit, "lmrob")) fit$rweights else fit$w
}

#' Note sentences for robust regression models
#'
#' The number of cases with weights near 0 is written by
#' `robust_low_sentence()` from the note record, so that lists of models
#' give it once.
#' @keywords internal
#' @noRd
robust_note_sentences <- function(fit) {
  weight_names <- c(
    huber = "Huber",
    bisquare = "bisquare",
    hampel = "Hampel",
    lqq = "linear quadratic quadratic (LQQ)",
    optimal = "optimal",
    ggw = "generalized Gauss-weight",
    welsh = "Welsh"
  )
  if (inherits(fit, "lmrob")) {
    method <- fit$control$method
    psi <- fit$control$psi
    estimator <- if (grepl("M$", method) && nchar(method) > 1) "MM" else method
    se_text <- "Standard errors are robust estimates."
  } else {
    method <- fit$call$method
    method <- if (is.null(method)) "M" else as.character(method)
    psi_call <- fit$call$psi
    psi <- if (identical(method, "MM")) {
      "bisquare"
    } else if (is.null(psi_call)) {
      "huber"
    } else {
      sub("^.*psi[.]", "", paste(deparse(psi_call), collapse = ""))
    }
    estimator <- method
    se_text <- "Standard errors are asymptotic estimates."
  }
  weight_name <- if (psi %in% names(weight_names)) weight_names[[psi]] else psi
  citation <- if (estimator == "MM") {
    cite("yohaiHighBreakdownpointHigh1987")
  } else {
    cite("huberRobustEstimationLocation1964")
  }
  c(
    paste0(
      "Estimates are from a robust regression using ",
      estimator,
      "-estimation with ",
      weight_name,
      " weights ",
      citation,
      "."
    ),
    se_text,
    n_sentence(length(robust_weights(fit)))
  )
}

#' Note sentence for the cases that robust regressions all but excluded
#' @param robust_low number of cases with weights below .10, one per model
#' @keywords internal
#' @noRd
robust_low_sentence <- function(robust_low) {
  if (length(robust_low) == 0 || all(robust_low == 0)) {
    return(character(0))
  }
  if (length(robust_low) == 1) {
    return(paste0(
      "Cases with weights below .10 (*n* = ",
      robust_low,
      ") had almost no influence on the estimates."
    ))
  }
  paste0(
    "Cases with weights below .10 had almost no influence on the estimates (*n* = ",
    and_list(robust_low),
    " in the models, in order)."
  )
}

Try the apa7 package in your browser

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

apa7 documentation built on Dec. 1, 2026, 5:06 p.m.