R/quantreg.R

Defines functions rq_note_sentences tau_text rq_performance pretty_parameter_names rq_coefficients apa_performance.rqs apa_performance.rq apa_parameters.rqs apa_parameters.rq

Documented in apa_parameters.rq apa_parameters.rqs apa_performance.rq apa_performance.rqs

# Quantile regression tables ----

#' @param se for quantile regression models, the method of computing standard
#'   errors, passed to `quantreg::summary.rq()`: `"nid"` (default) for
#'   Hendricks-Koenker sandwich estimates, which allow the errors to differ
#'   across cases, `"iid"` for estimates that assume independent and
#'   identically distributed errors, `"ker"` for Powell kernel estimates, or
#'   `"boot"` for bootstrap estimates. (quantreg's own default for fewer than
#'   1,000 cases, `"rank"`, gives confidence intervals without standard
#'   errors.)
#' @param ci for quantile regression (`quantreg::rq`), `lavaan`, and
#'   generalized estimating equation (`geepack::geeglm`) models,
#'   the confidence level of the intervals shown when `predictor_parameters`
#'   includes `"CI"` (default .95). For other models, pass `ci` in `...` to
#'   [parameters::model_parameters()].
#' @param quantiles for quantile regression models with several quantiles
#'   (`quantreg::rq(tau = c(.25, .5, .75))`), `"columns"` (default) to show
#'   each quantile's estimates side by side under a column spanner (e.g.,
#'   "\eqn{\tau}{tau} = .25"), or `"rows"` to stack them under heading rows
#' @details
#' For quantile regression models (`quantreg::rq`), coefficients are the
#' change in a quantile of the outcome (e.g., the median, with `tau = .5`)
#' per unit of the predictor, tested with *t* tests of the coefficient
#' divided by its standard error (see `se`). [apa_note()] names the quantile
#' and the kind of standard errors. Models with several quantiles show the
#' estimates of each quantile side by side (see `quantiles`).
#' @references
#' Hendricks, W., & Koenker, R. (1992). Hierarchical spline models for
#' conditional quantiles and the demand for electricity. *Journal of the
#' American Statistical Association, 87*(417), 58--68.
#' \doi{10.1080/01621459.1992.10475175}
#'
#' Koenker, R., & Bassett, G. (1978). Regression quantiles. *Econometrica,
#' 46*(1), 33--50. \doi{10.2307/1913643}
#'
#' Koenker, R., & Machado, J. A. F. (1999). Goodness of fit and related
#' inference processes for quantile regression. *Journal of the American
#' Statistical Association, 94*(448), 1296--1310.
#' \doi{10.1080/01621459.1999.10473882}
#' @export
#' @rdname apa_parameters
#' @examples
#' \donttest{
#' if (requireNamespace("quantreg", quietly = TRUE) &&
#'     requireNamespace("psych", quietly = TRUE)) {
#'   d <- psych::sat.act
#'   d$female <- as.integer(d$gender == 2)
#'   # ACT scores at the 25th, 50th, and 75th percentiles
#'   quantreg::rq(ACT ~ education + female, tau = c(.25, .5, .75), data = d) |>
#'     suppressWarnings() |>
#'     apa_parameters()
#' }
#' }
apa_parameters.rq <- function(
  fit,
  predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  se = c("nid", "iid", "ker", "boot"),
  ci = .95,
  ...
) {
  rlang::check_installed("quantreg", reason = "for quantile regression tables.")
  se <- match.arg(se)
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL
  s <- summary(fit, se = se, ...)
  format_apa_parameters(
    rq_coefficients(s, fit, ci),
    predictor_parameters = predictor_parameters,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats,
    t_with_df = t_with_df,
    note = list(model_sentences = rq_note_sentences(fit, fit$tau, se))
  )
}

#' @export
#' @rdname apa_parameters
apa_parameters.rqs <- function(
  fit,
  predictor_parameters = c("Parameter", "Coefficient", "SE", "t", "df_error", "p"),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  se = c("nid", "iid", "ker", "boot"),
  ci = .95,
  quantiles = c("columns", "rows"),
  ...
) {
  rlang::check_installed("quantreg", reason = "for quantile regression tables.")
  se <- match.arg(se)
  quantiles <- match.arg(quantiles)
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL
  summaries <- summary(fit, se = se, ...)
  taus <- fit$tau
  labels <- paste0("*&tau;* = ", tau_text(taus))
  note <- list(model_sentences = rq_note_sentences(fit, taus, se))

  if (quantiles == "rows") {
    # Each quantile's estimates under a heading row, with the names formatted
    # here because the headings are added below
    name_formatter <- column_formats$Parameter@formatter
    pieces <- purrr::map(seq_along(taus), \(i) {
      block <- rq_coefficients(summaries[[i]], fit, ci)
      block$Parameter <- paste0("\u2003", name_formatter(block$Parameter))
      dplyr::bind_rows(tibble::tibble(Parameter = labels[i]), block)
    })
    column_formats$Parameter@formatter <- \(x, ...) x
    return(
      format_apa_parameters(
        dplyr::bind_rows(pieces),
        predictor_parameters = predictor_parameters,
        starred = starred,
        bolded = bolded,
        column_formats = column_formats,
        t_with_df = t_with_df,
        note = note
      ) |>
        labels_formatted()
    )
  }

  # Side by side: one table per quantile, joined under column spanners
  tables <- purrr::map(seq_along(taus), \(i) {
    format_apa_parameters(
      rq_coefficients(summaries[[i]], fit, ci),
      predictor_parameters = predictor_parameters,
      starred = starred,
      bolded = bolded,
      column_formats = column_formats,
      t_with_df = t_with_df,
      note = note
    )
  })
  record <- attr(tables[[1]], "apa_note", exact = TRUE)
  first <- colnames(tables[[1]])[1]
  pieces <- purrr::map(seq_along(tables), \(i) {
    tb <- tibble::as_tibble(tables[[i]])
    stats <- setdiff(colnames(tb), first)
    tb <- tb[stats]
    colnames(tb) <- paste0(labels[i], "_", stats)
    tb
  })
  out <- dplyr::bind_cols(tibble::as_tibble(tables[[1]])[first], pieces)
  attr(out, "apa_note") <- record
  as_apa7_tbl(out)
}

#' @details
#' For quantile regression models (`quantreg::rq`), `R1` is the
#' Koenker-Machado goodness of fit, *R*^1^: the proportional reduction in the
#' sum of weighted absolute residuals from the model with only an intercept
#' at the same quantile. It is the quantile regression counterpart of
#' *R*^2^, and it is usually smaller. The default metrics are `R1` and `AIC`.
#' Models with several quantiles get a row for each quantile. Lists of models
#' are compared in [apa_performance_comparison()] by *R*^1^ and *AIC*,
#' without tests.
#' @export
#' @rdname apa_performance
apa_performance.rq <- function(
  fit,
  metrics = c("R1", "AIC"),
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- c("R1", "AIC", "BIC")
  }
  format_performance(rq_performance(fit), metrics, column_formats)
}

#' @export
#' @rdname apa_performance
apa_performance.rqs <- function(
  fit,
  metrics = c("R1", "AIC"),
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- c("R1", "AIC", "BIC")
  }
  d <- format_performance(rq_performance(fit), metrics, column_formats)
  tibble::add_column(d, Quantile = tau_text(fit$tau), .before = 1) |>
    as_apa7_tbl()
}

# Coefficients and fit statistics ----

#' Coefficients of a quantile regression model
#' @param s a `summary.rq` object
#' @keywords internal
#' @noRd
rq_coefficients <- function(s, fit, ci) {
  co <- s$coefficients
  df <- s$rdf
  half <- stats::qt(1 - (1 - ci) / 2, df) * co[, 2]
  tibble::tibble(
    Parameter = pretty_parameter_names(fit, rownames(co)),
    Coefficient = co[, 1],
    SE = co[, 2],
    CI = ci,
    CI_low = co[, 1] - half,
    CI_high = co[, 1] + half,
    t = co[, 3],
    df_error = df,
    p = co[, 4]
  )
}

#' Readable parameter names from parameters (e.g., Gender with its level)
#'
#' Names are matched without backticks, which parameters keeps for some
#' models (e.g., `coxph`) when variable names have spaces.
#' @param raw parameter names as the model or parameters gives them
#' @keywords internal
#' @noRd
pretty_parameter_names <- function(fit, raw) {
  pretty <- parameters::format_parameters(fit)
  names(pretty) <- gsub("`", "", names(pretty), fixed = TRUE)
  out <- unname(pretty[gsub("`", "", raw, fixed = TRUE)])
  out[is.na(out)] <- raw[is.na(out)]
  out
}

#' Fit statistics of a quantile regression model, one row per quantile
#' @keywords internal
#' @noRd
rq_performance <- function(fit) {
  taus <- fit$tau
  y <- fit$y
  if (is.null(y)) {
    y <- stats::model.response(stats::model.frame(fit))
  }
  res <- as.matrix(stats::residuals(fit))
  check_loss <- function(u, tau) sum(u * (tau - (u < 0)))
  r1 <- purrr::map_dbl(seq_along(taus), \(i) {
    # The intercept-only model at a quantile is the sample quantile
    q <- stats::quantile(y, taus[i], type = 1, names = FALSE)
    1 - check_loss(res[, i], taus[i]) / check_loss(y - q, taus[i])
  })
  tibble::tibble(
    R1 = r1,
    AIC = as.numeric(stats::AIC(fit)),
    BIC = as.numeric(stats::AIC(fit, k = log(length(y))))
  )
}

# Note sentences ----

#' Quantiles as text without leading zeros (e.g., .25 and .50)
#' @keywords internal
#' @noRd
tau_text <- function(tau) {
  vapply(tau, \(x) {
    # At least two decimals (.50), and more if needed (.333)
    digits <- max(2, nchar(sub("^[^.]*[.]?", "", as.character(x))))
    sub("^0", "", formatC(x, format = "f", digits = digits))
  }, character(1))
}

#' Note sentences for quantile regression models
#' @keywords internal
#' @noRd
rq_note_sentences <- function(fit, taus, se) {
  response <- variable_name_formatter(insight::find_response(fit))
  koenker <- cite("koenkerRegressionQuantiles1978")
  model_text <- if (length(taus) > 1) {
    paste0("quantile regressions ", koenker, " of ", response, " at *&tau;* = ", and_list(tau_text(taus)))
  } else if (taus == .5) {
    paste0("a quantile regression ", koenker, " of the median of ", response, " (*&tau;* = .50)")
  } else {
    paste0(
      "a quantile regression ", koenker, " of the ", tau_text(taus), " quantile of ",
      response, " (*&tau;* = ", tau_text(taus), ")"
    )
  }
  se_text <- c(
    nid = paste0("Hendricks", intToUtf8(8211), "Koenker sandwich estimates ", cite("hendricksHierarchicalSplineModels1992")),
    iid = "estimates that assume independent and identically distributed errors",
    ker = "Powell kernel estimates",
    boot = "bootstrap estimates"
  )
  c(
    paste0("Estimates are from ", model_text, "."),
    paste0("Standard errors are ", se_text[[se]], "."),
    n_sentence(NROW(fit$residuals))
  )
}

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.