R/list_rows.R

Defines functions lme_refit test_row_definition test_rows lme4_bars null_model stored_null_test null_lrt null_test pairwise_tests change_tests list_row_defaults

# Default statistics for the rows of lists of models in apa_parameters()
# (performance_layout = "rows"): each model's fit, the change in fit, the test
# of the change (starred, with its degrees of freedom in the label), and
# information criteria. The first model is tested against a model with only a
# constant (and the random effects of mixed models). See CONVENTIONS.md
# (TAB-7).

# Default rows of lists of models ----

#' Default statistics for the rows of a list of models
#'
#' @param models list of fitted models
#' @returns list of `fit` (metrics shown before the test, e.g., `"R2"` and
#'   `"deltaR2"`), `test` (`"F"`, `"chisq"`, `"wald"`, or `NULL` for none),
#'   and `extra` (metrics after the test, e.g., `"AIC"`), or `NULL` when the
#'   models are of different kinds or of a kind without defaults
#' @keywords internal
#' @noRd
list_row_defaults <- function(models) {
  all_of_class <- function(cls) {
    length(models) > 0 && all(purrr::map_lgl(models, \(m) inherits(m, cls)))
  }
  if (all_of_class("rq")) {
    return(list(fit = "R1", test = NULL, extra = "AIC"))
  }
  if (all_of_class("rlm")) {
    return(list(fit = "Sigma_robust", test = NULL, extra = character(0)))
  }
  if (all_of_class("lmrob")) {
    return(list(fit = c("R2", "deltaR2"), test = "wald", extra = character(0)))
  }
  if (all_of_class("gam")) {
    return(list(fit = c("R2", "deltaR2"), test = NULL, extra = "AIC"))
  }
  if (all_of_class(c("merMod", "glmmTMB", "lme", "clmm"))) {
    return(list(fit = c("R2", "R2_conditional"), test = "chisq", extra = "AIC"))
  }
  if (all_of_class(c("coxph", "survreg"))) {
    return(list(fit = c("R2", "Concordance"), test = "chisq", extra = "AIC"))
  }
  if (all_of_class("betareg") || all_of_class(c("polr", "clm", "multinom"))) {
    return(list(fit = "R2", test = "chisq", extra = "AIC"))
  }
  if (all_of_class(c("zeroinfl", "hurdle"))) {
    return(list(fit = character(0), test = "chisq", extra = "AIC"))
  }
  # GEE models have no likelihood: QIC and Wald tests of the added terms
  if (all_of_class("geeglm")) {
    return(list(fit = "QIC", test = "gee", extra = character(0)))
  }
  if (all_of_class("glm")) {
    if (all(purrr::map_lgl(models, has_fixed_dispersion))) {
      return(list(fit = "R2", test = "chisq", extra = "AIC"))
    }
    return(list(fit = c("R2", "deltaR2"), test = "F", extra = character(0)))
  }
  # glm objects inherit from lm, so a list of lm models has no glm in it
  if (all_of_class("lm") && !any(purrr::map_lgl(models, \(m) inherits(m, "glm")))) {
    return(list(fit = c("R2", "deltaR2"), test = "F", extra = character(0)))
  }
  NULL
}

# Tests of change ----

#' Test of each model's change in fit
#'
#' Each model is tested against the one before it, and the first against a
#' model with only a constant (and the random effects of mixed models).
#' @param test `"F"`, `"chisq"`, `"wald"`, or `"gee"`
#' @returns tibble with `statistic`, `df1`, `df2` (`NA` except for *F*), and
#'   `p`, one row per model (`NA` where a test could not be computed)
#' @keywords internal
#' @noRd
change_tests <- function(models, test) {
  first <- null_test(models[[1]], test)
  rest <- if (length(models) > 1) {
    pairwise_tests(models, test)[-1, , drop = FALSE]
  }
  dplyr::bind_rows(first, rest)
}

#' Tests of each model against the one before it (the first row is empty)
#' @keywords internal
#' @noRd
pairwise_tests <- function(models, test) {
  empty <- tibble::tibble(statistic = NA_real_, df1 = NA_real_, df2 = NA_real_, p = NA_real_)
  out <- tryCatch(
    {
      if (test == "wald") {
        w <- lmrob_wald_tests(models)
        tibble::tibble(statistic = w$Chi2, df1 = w$df, df2 = NA_real_, p = w$p)
      } else if (test == "gee") {
        w <- gee_wald_tests(models)
        tibble::tibble(statistic = w$Chi2, df1 = w$df, df2 = NA_real_, p = w$p)
      } else if (test == "chisq") {
        t <- tibble::as_tibble(suppressMessages(muffle_backtick_warning(
          do.call(performance::test_likelihoodratio, unname(models))
        )))
        tibble::tibble(statistic = t$Chi2, df1 = abs(t$df_diff), df2 = NA_real_, p = t$p)
      } else {
        t <- tibble::as_tibble(suppressMessages(muffle_backtick_warning(
          do.call(performance::test_wald, unname(models))
        )))
        tibble::tibble(statistic = t$F, df1 = abs(t$df_diff), df2 = t$df, p = t$p)
      }
    },
    error = function(e) NULL
  )
  if (is.null(out) || nrow(out) != length(models)) {
    out <- empty[rep(1, length(models)), ]
  }
  out
}

# Tests against the null model ----

#' Test of a model against a model with only a constant
#'
#' Uses what the model stores where it can (the overall *F* test of `lm`, the
#' deviances of `glm`, and the likelihood ratio tests of `coxph` and
#' `survreg`). Otherwise, the model with only a constant (and the random
#' effects of mixed models) is fit to the same cases and tested as the other
#' models are.
#' @keywords internal
#' @noRd
null_test <- function(fit, test) {
  empty <- tibble::tibble(statistic = NA_real_, df1 = NA_real_, df2 = NA_real_, p = NA_real_)
  stored <- tryCatch(stored_null_test(fit, test), error = function(e) NULL)
  if (!is.null(stored)) {
    return(stored)
  }
  null_fit <- tryCatch(null_model(fit), error = function(e) NULL)
  if (is.null(null_fit)) {
    return(empty)
  }
  if (test == "chisq") {
    return(tryCatch(null_lrt(null_fit, fit), error = function(e) empty))
  }
  out <- pairwise_tests(list(null_fit, fit), test)
  out[2, , drop = FALSE]
}

#' Likelihood ratio test of a model against its null model
#'
#' Computed from the log-likelihoods, because performance::test_likelihoodratio()
#' looks for the data of each model and cannot find the null model's. Models
#' fit by REML are refit by maximum likelihood, because their fixed effects
#' differ.
#' @keywords internal
#' @noRd
null_lrt <- function(null_fit, fit) {
  if (inherits(fit, "merMod") && lme4::isREML(fit)) {
    fit <- lme4::refitML(fit)
    null_fit <- lme4::refitML(null_fit)
  }
  if (inherits(fit, "lme") && identical(fit$method, "REML")) {
    fit <- lme_refit(fit)
  }
  ll1 <- stats::logLik(fit)
  ll0 <- stats::logLik(null_fit)
  chisq <- 2 * (as.numeric(ll1) - as.numeric(ll0))
  df <- attr(ll1, "df") - attr(ll0, "df")
  tibble::tibble(
    statistic = chisq,
    df1 = df,
    df2 = NA_real_,
    p = stats::pchisq(chisq, df, lower.tail = FALSE)
  )
}

#' Null test from what a model stores, or NULL
#' @keywords internal
#' @noRd
stored_null_test <- function(fit, test) {
  # GEE models have no likelihood or deviance test, so the null model is refit
  if (inherits(fit, "geeglm")) {
    return(NULL)
  }
  if (inherits(fit, c("coxph"))) {
    lt <- summary(fit)$logtest
    return(tibble::tibble(statistic = unname(lt[["test"]]), df1 = unname(lt[["df"]]), df2 = NA_real_, p = unname(lt[["pvalue"]])))
  }
  if (inherits(fit, "survreg")) {
    chisq <- 2 * diff(fit$loglik)
    df <- sum(fit$df) - fit$idf
    return(tibble::tibble(statistic = chisq, df1 = df, df2 = NA_real_, p = stats::pchisq(chisq, df, lower.tail = FALSE)))
  }
  if (inherits(fit, "glm")) {
    change <- fit$null.deviance - fit$deviance
    df1 <- fit$df.null - fit$df.residual
    if (test == "chisq") {
      return(tibble::tibble(statistic = change, df1 = df1, df2 = NA_real_, p = stats::pchisq(change, df1, lower.tail = FALSE)))
    }
    dispersion <- summary(fit)$dispersion
    f <- (change / df1) / dispersion
    return(tibble::tibble(statistic = f, df1 = df1, df2 = fit$df.residual, p = stats::pf(f, df1, fit$df.residual, lower.tail = FALSE)))
  }
  if (inherits(fit, "lm") && !inherits(fit, c("rlm", "lmrob")) && test == "F") {
    fs <- summary(fit)$fstatistic
    if (is.null(fs)) {
      return(NULL)
    }
    return(tibble::tibble(
      statistic = unname(fs[["value"]]),
      df1 = unname(fs[["numdf"]]),
      df2 = unname(fs[["dendf"]]),
      p = stats::pf(fs[["value"]], fs[["numdf"]], fs[["dendf"]], lower.tail = FALSE)
    ))
  }
  NULL
}

#' A model with only a constant (and the random effects of mixed models),
#' fit to the same cases as `fit`
#' @keywords internal
#' @noRd
null_model <- function(fit) {
  if (inherits(fit, "lme")) {
    # By maximum likelihood, because its fixed effects differ from the model's
    # (null_lrt() refits the model by maximum likelihood, too)
    return(lme_refit(fit, fixed = stats::update(stats::formula(fit), . ~ 1)))
  }
  f <- stats::formula(fit)
  used <- stats::model.frame(fit)
  # The original data, limited to the cases the model used, so that the
  # response (e.g., factor(gear)) and any weights are found as in the model
  data <- tryCatch(
    {
      original <- eval(fit$call$data, environment(f))
      original[rownames(used), , drop = FALSE]
    },
    error = function(e) NULL
  )
  if (is.null(data)) {
    data <- used
  }
  response <- paste(deparse(f[[2]]), collapse = "")
  bars <- if (inherits(fit, c("merMod", "glmmTMB", "clmm"))) lme4_bars(f)
  new_formula <- stats::as.formula(
    paste(response, "~", paste(c("1", bars), collapse = " + ")),
    env = environment(f)
  )
  stats::update(fit, formula. = new_formula, data = data)
}

#' Random-effect terms of a mixed-model formula, as text (e.g., "(1 | id)")
#' @keywords internal
#' @noRd
lme4_bars <- function(f) {
  rlang::check_installed("lme4", reason = "for the tests of mixed models.")
  # lme4 warns that findbars() has moved to the reformulas package
  bars <- suppressWarnings(lme4::findbars(f))
  vapply(bars, \(b) paste0("(", paste(deparse(b), collapse = ""), ")"), character(1))
}

# Test rows and their note ----

#' Rows of the tests of change, one per model
#' @param tests output of change_tests()
#' @returns tibble with `Model`, `label` (e.g., "*F*(1, 29)"), and `value`
#'   (the statistic with stars)
#' @keywords internal
#' @noRd
test_rows <- function(tests, models, test) {
  # Each df on its own, so that they are not padded to a common width
  df_text <- function(x) {
    vapply(x, \(v) {
      if (is.na(v)) {
        NA_character_
      } else if (abs(v - round(v)) < 1e-8) {
        formatC(round(v), format = "d", big.mark = ",")
      } else {
        sprintf("%.2f", v)
      }
    }, character(1))
  }
  label <- if (test == "F") {
    paste0("*F*(", df_text(tests$df1), ", ", df_text(tests$df2), ")")
  } else {
    paste0("*&chi;*^2^(", df_text(tests$df1), ")")
  }
  stars <- p2stars(tests$p, superscript = TRUE)
  stars[is.na(stars)] <- ""
  value <- paste0(align_chr(tests$statistic, accuracy = the$accuracy), stars)
  # A model that already has only a constant (df = 0) is not tested against
  # itself
  keep <- !is.na(tests$statistic) & !is.na(tests$df1) & tests$df1 > 0
  tibble::tibble(Model = models, label = label, value = value)[keep, , drop = FALSE]
}

#' Note definition of the test rows
#' @keywords internal
#' @noRd
test_row_definition <- function(test, mixed) {
  null_text <- if (mixed) {
    "for the first model, from a model with only a constant and the random effects"
  } else {
    "for the first model, from a model with only a constant"
  }
  kind <- switch(test,
    F = "test",
    chisq = "likelihood ratio test",
    wald = "robust Wald test",
    gee = "Wald test"
  )
  symbol <- if (test == "F") "*F*" else "*&chi;*^2^"
  stats::setNames(
    paste0(kind, " of the change in fit from the previous model (", null_text, ")"),
    symbol
  )
}

# Refitting nlme models ----

#' Refit an nlme::lme model by maximum likelihood, optionally with other
#' fixed effects
#'
#' The call of an lme model names lme.formula(), which cannot be found unless
#' nlme is attached, so the call is rebuilt with nlme::lme().
#' @keywords internal
#' @noRd
lme_refit <- function(fit, fixed = NULL) {
  cl <- fit$call
  cl[[1]] <- quote(nlme::lme)
  cl$method <- "ML"
  cl$data <- nlme::getData(fit)
  if (!is.null(fixed)) {
    cl$fixed <- fixed
  }
  eval(cl, environment(stats::formula(fit)))
}

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.