R/manova.R

Defines functions manova_univariate manova_note_sentences apa_manova_table manova_statistic manova_tests apa_anova.Anova.mlm apa_anova.mlm

Documented in apa_anova.Anova.mlm apa_anova.mlm

# MANOVA tables ----

#' @details
#' For multivariate analyses of variance, from [stats::manova()] or from
#' [stats::lm()] with several outcomes (`lm(cbind(y1, y2) ~ x)`), the table
#' has a row for each effect with its multivariate test statistic (Pillai's
#' trace by default; `test` chooses Wilks's lambda, the Hotelling--Lawley
#' trace, or Roy's largest root), its approximate *F* test (*df*~1~,
#' *df*~2~, *p*), and partial \eqn{\eta^2}{eta^2}, computed from the
#' approximate *F* and its degrees of freedom (e.g., [effectsize::F_to_eta2()]).
#' Sums of squares are sequential (Type I) by default, as in
#' [stats::summary.manova()]; `type = 2` or `3` gives `car::Anova()` tests.
#' `car::Anova()` tables of such models (class `Anova.mlm`) are displayed the
#' same way. The intercept is not shown. With `univariate = TRUE`, the table
#' instead shows the univariate ANOVA of each outcome, under a heading row
#' for each outcome, as a follow-up to the multivariate tests.
#' @param test for multivariate models, the multivariate test statistic:
#'   `"Pillai"` (default), `"Wilks"`, `"Hotelling-Lawley"`, or `"Roy"`. For
#'   `car::Anova()` tables, the statistic of the table by default.
#' @param univariate for multivariate models, if `TRUE`, the univariate ANOVA
#'   of each outcome instead of the multivariate tests. The outcomes must be
#'   given with `cbind()` in the model formula.
#' @references
#' Pillai, K. C. S. (1955). Some new test criteria in multivariate analysis.
#' *The Annals of Mathematical Statistics, 26*(1), 117--121.
#' \doi{10.1214/aoms/1177728599}
#'
#' Wilks, S. S. (1932). Certain generalizations in the analysis of variance.
#' *Biometrika, 24*(3/4), 471--494. \doi{10.1093/biomet/24.3-4.471}
#' @export
#' @rdname apa_anova
#' @examples
#' # Multivariate analysis of variance
#' if (requireNamespace("carData", quietly = TRUE)) {
#'   fit_manova <- manova(
#'     cbind(post.test.1, post.test.2, post.test.3) ~ group,
#'     data = carData::Baumann
#'   )
#'   apa_anova(fit_manova)
#'   apa_anova(fit_manova, test = "Wilks")
#'   # Univariate follow-ups
#'   apa_anova(fit_manova, univariate = TRUE)
#' }
apa_anova.mlm <- function(
  fit,
  anova_parameters = manova_anova_parameters,
  effect_size = c("eta", "omega", "epsilon"),
  partial = TRUE,
  generalized = FALSE,
  type = NULL,
  ci = 0.95,
  residual_label = "Error",
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  test = c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"),
  univariate = FALSE,
  ...
) {
  type <- anova_ss_type(type)
  if (isTRUE(univariate)) {
    return(manova_univariate(
      fit,
      type = type,
      anova_parameters = if (missing(anova_parameters)) NULL else anova_parameters,
      effect_size = effect_size,
      partial = partial,
      generalized = generalized,
      ci = ci,
      residual_label = residual_label,
      starred = starred,
      bolded = bolded,
      column_formats = column_formats,
      ...
    ))
  }
  test <- match.arg(test)
  if (type == 1) {
    s <- stats::summary.manova(fit)
    terms <- setdiff(names(s$SS), "Residuals")
    tests <- manova_tests(
      SSP = s$SS[terms],
      SSPE = s$SS[["Residuals"]],
      df = stats::setNames(s$stats[terms, "Df"], terms),
      error_df = s$stats["Residuals", "Df"],
      test = test
    )
  } else {
    rlang::check_installed("car", reason = "for Type 2 and 3 sums of squares.")
    a <- car::Anova(fit, type = type)
    tests <- manova_tests(a$SSP, a$SSPE, a$df, a$error.df, test)
  }
  apa_manova_table(
    tests,
    test = test,
    ss_type = type,
    outcomes = colnames(stats::residuals(fit)),
    n = nrow(stats::residuals(fit)),
    anova_parameters = anova_parameters,
    effect_size = effect_size,
    partial = partial,
    generalized = generalized,
    ci = ci,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats
  )
}

#' @export
#' @rdname apa_anova
apa_anova.manova <- apa_anova.mlm

#' @export
#' @rdname apa_anova
apa_anova.Anova.mlm <- function(
  fit,
  anova_parameters = manova_anova_parameters,
  effect_size = c("eta", "omega", "epsilon"),
  partial = TRUE,
  generalized = FALSE,
  type = NULL,
  ci = 0.95,
  residual_label = "Error",
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  test = NULL,
  univariate = FALSE,
  ...
) {
  if (isTRUE(fit$repeated)) {
    cli::cli_abort(c(
      "{.fn apa_anova} does not support repeated-measures multivariate tests.",
      i = "Use {.fn afex::aov_car} for repeated-measures designs."
    ))
  }
  if (isTRUE(univariate)) {
    cli::cli_abort(c(
      "{.fn car::Anova} tables do not keep the model, so they have no univariate follow-ups.",
      i = "Pass the model to {.fn apa_anova} with {.code univariate = TRUE} instead."
    ))
  }
  if (!is.null(type)) {
    cli::cli_warn("{.arg type} is ignored for ANOVA tables, which already have a type of sums of squares.")
  }
  test <- if (is.null(test)) fit$test else test
  test <- match.arg(test, c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"))
  tests <- manova_tests(fit$SSP, fit$SSPE, fit$df, fit$error.df, test)
  apa_manova_table(
    tests,
    test = test,
    ss_type = anova_ss_type(fit$type),
    outcomes = colnames(fit$SSPE),
    n = NULL,
    anova_parameters = anova_parameters,
    effect_size = effect_size,
    partial = partial,
    generalized = generalized,
    ci = ci,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats
  )
}

# Multivariate test statistics ----

#' Columns of MANOVA tables
#' @keywords internal
#' @noRd
manova_anova_parameters <- c(
  "Parameter",
  "Statistic",
  "F",
  "df",
  "df_error",
  "p",
  "Effect_Size"
)

#' Column format names of the multivariate test statistics
#' @keywords internal
#' @noRd
manova_statistic_columns <- c(
  Pillai = "Pillai",
  Wilks = "Wilks",
  `Hotelling-Lawley` = "Hotelling_Lawley",
  Roy = "Roy"
)

#' Multivariate tests of each effect from its hypothesis and error SSP
#' matrices, with the approximate F tests of stats::summary.manova()
#' @param SSP named list of hypothesis SSP matrices
#' @param SSPE error SSP matrix
#' @param df,error_df degrees of freedom of the effects and of the error
#' @keywords internal
#' @noRd
manova_tests <- function(SSP, SSPE, df, error_df, test) {
  error_qr <- qr(SSPE)
  rows <- lapply(names(SSP), \(term) {
    eig <- Re(eigen(qr.coef(error_qr, SSP[[term]]), symmetric = FALSE)$values)
    stat <- manova_statistic(eig, q = df[[term]], df_res = error_df, test = test)
    tibble::tibble(
      Parameter = term,
      Statistic = stat[1],
      F = stat[2],
      df = stat[3],
      df_error = stat[4],
      p = stats::pf(stat[2], stat[3], stat[4], lower.tail = FALSE)
    )
  })
  d <- dplyr::bind_rows(rows)
  d[d$Parameter != "(Intercept)", ]
}

#' Statistic, approximate F, and its degrees of freedom (the approximations
#' of stats::summary.manova())
#' @param eig eigenvalues of solve(SSPE) %*% SSP
#' @param q hypothesis degrees of freedom
#' @param df_res error degrees of freedom
#' @keywords internal
#' @noRd
manova_statistic <- function(eig, q, df_res, test) {
  p <- length(eig)
  s <- min(p, q)
  m <- 0.5 * (abs(p - q) - 1)
  n <- 0.5 * (df_res - p - 1)
  switch(
    test,
    Pillai = {
      v <- sum(eig / (1 + eig))
      tmp1 <- 2 * m + s + 1
      tmp2 <- 2 * n + s + 1
      c(v, (tmp2 / tmp1 * v) / (s - v), s * tmp1, s * tmp2)
    },
    Wilks = {
      lambda <- prod(1 / (1 + eig))
      tmp1 <- df_res - 0.5 * (p - q + 1)
      tmp2 <- (p * q - 2) / 4
      tmp3 <- p^2 + q^2 - 5
      tmp3 <- if (tmp3 > 0) sqrt(((p * q)^2 - 4) / tmp3) else 1
      c(
        lambda,
        ((lambda^(-1 / tmp3) - 1) * (tmp1 * tmp3 - 2 * tmp2)) / p / q,
        p * q,
        tmp1 * tmp3 - 2 * tmp2
      )
    },
    `Hotelling-Lawley` = {
      t <- sum(eig)
      tmp1 <- 2 * m + s + 1
      tmp2 <- 2 * (s * n + 1)
      c(t, (tmp2 * t) / s / s / tmp1, s * tmp1, tmp2)
    },
    Roy = {
      theta <- max(eig)
      tmp1 <- max(p, q)
      tmp2 <- df_res - tmp1 + q
      c(theta, (tmp2 * theta) / tmp1, tmp1, tmp2)
    }
  )
}

# Formatting MANOVA tables ----

#' Format the multivariate tests
#' @keywords internal
#' @noRd
apa_manova_table <- function(
  d,
  test,
  ss_type,
  outcomes,
  n,
  anova_parameters,
  effect_size,
  partial,
  generalized,
  ci,
  starred,
  bolded,
  column_formats,
  call = rlang::caller_env()
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(anova_parameters) <- NULL

  if (!is.null(effect_size)) {
    effect_size <- match.arg(effect_size, c("eta", "omega", "epsilon"))
    if (isTRUE(generalized)) {
      cli::cli_abort("Generalized effect sizes are not available for multivariate tests.", call = call)
    }
    if (!isTRUE(partial)) {
      cli::cli_abort("Only partial effect sizes are available for multivariate tests.", call = call)
    }
  }
  column_formats <- es_ci_format(column_formats)
  show_ci <- "CI" %in% anova_parameters && !is.null(effect_size)

  # The statistic's column is named for it
  stat_col <- manova_statistic_columns[[test]]
  names(d)[names(d) == "Statistic"] <- stat_col
  anova_parameters[anova_parameters == "Statistic"] <- stat_col

  # Partial effect sizes from the approximate F and its degrees of freedom
  es_col <- NA_character_
  if (!is.null(effect_size)) {
    es_fun <- switch(
      effect_size,
      eta = effectsize::F_to_eta2,
      omega = effectsize::F_to_omega2,
      epsilon = effectsize::F_to_epsilon2
    )
    d_es <- es_fun(
      d$F,
      d$df,
      d$df_error,
      ci = if (show_ci) ci else NULL,
      alternative = "two.sided"
    ) |>
      tibble::as_tibble()
    es_col <- intersect(colnames(d_es), anova_es_columns)[1]
    d[[es_col]] <- d_es[[es_col]]
    if (show_ci && all(c("CI_low", "CI_high") %in% colnames(d_es))) {
      d$CI_low <- d_es$CI_low
      d$CI_high <- d_es$CI_high
      d$CI <- ci
    }
  }
  if (is.na(es_col)) {
    anova_parameters <- setdiff(anova_parameters, c("Effect_Size", "CI"))
  } else {
    anova_parameters[anova_parameters == "Effect_Size"] <- es_col
    if (!("CI_low" %in% colnames(d))) {
      anova_parameters <- setdiff(anova_parameters, "CI")
    }
  }

  d$Parameter <- gsub(":", " \u00D7 ", d$Parameter, fixed = TRUE)

  if (column_formats$Parameter@header == "Variable") {
    column_formats$Parameter@header <- "Effect"
    column_formats$Parameter@latex <- "Effect"
  }
  if (!is.null(column_formats$df)) {
    column_formats$df@header <- "*df*~1~"
    column_formats$df@latex <- "$df_1$"
  }
  if (!is.null(column_formats$df_error)) {
    column_formats$df_error@header <- "*df*~2~"
    column_formats$df_error@latex <- "$df_2$"
  }

  d_new <- format_apa_parameters(
    d,
    predictor_parameters = anova_parameters,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats,
    t_with_df = FALSE
  )

  attr(d_new, "apa_note") <- anova_note_record(
    ss_type = ss_type,
    abbreviations = attr(d_new, "apa_note", exact = TRUE)$abbreviations,
    starred = anova_marked(starred, anova_parameters),
    bolded = anova_marked(bolded, anova_parameters),
    model_sentences = manova_note_sentences(
      outcomes = column_formats$Parameter@formatter(outcomes),
      n = n,
      effect_size_header = if (is.na(es_col)) NULL else column_formats[[es_col]]@header
    )
  )

  as_apa7_tbl(d_new)
}

# Note sentences ----

#' "Multivariate tests of A, B, and C, with approximate *F* tests. *N* = 66.
#' ..."
#' @keywords internal
#' @noRd
manova_note_sentences <- function(outcomes, n = NULL, effect_size_header = NULL) {
  sentences <- c(
    paste0(
      "Multivariate tests of ",
      and_list(outcomes),
      ", with approximate *F* tests."
    ),
    if (!is.null(n)) n_sentence(n)
  )
  if (!is.null(effect_size_header)) {
    sentences <- c(
      sentences,
      paste0(effect_size_header, " is computed from the approximate *F* and its degrees of freedom.")
    )
  }
  sentences
}

# Univariate follow-up ANOVAs ----

#' Univariate ANOVA of each outcome of a multivariate model, under a heading
#' row for each outcome
#' @keywords internal
#' @noRd
manova_univariate <- function(fit, type, anova_parameters, ..., column_formats = NULL, call = rlang::caller_env()) {
  response <- stats::formula(fit)[[2]]
  if (!is.call(response) || !identical(response[[1]], as.name("cbind"))) {
    cli::cli_abort(
      "Univariate follow-ups need the outcomes in {.fn cbind} in the model formula (e.g., {.code cbind(y1, y2) ~ x}).",
      call = call
    )
  }
  outcomes <- as.list(response)[-1]
  outcome_names <- colnames(stats::residuals(fit))

  # Refit each outcome with lm()
  fit_call <- fit$call
  fit_call[[1]] <- quote(stats::lm)
  fit_call <- match.call(stats::lm, fit_call)
  env <- environment(stats::terms(fit))
  if (is.null(env)) {
    env <- parent.frame() # nocov
  }
  tables <- lapply(outcomes, \(y) {
    f <- stats::formula(fit)
    f[[2]] <- y
    one_call <- fit_call
    one_call$formula <- f
    one_fit <- eval(one_call, env)
    args <- list(one_fit, type = type, column_formats = column_formats, ...)
    if (!is.null(anova_parameters)) {
      args$anova_parameters <- anova_parameters
    }
    do.call(apa_anova.lm, args)
  })
  note <- attr(tables[[1]], "apa_note", exact = TRUE)

  formatter <- if (is.null(column_formats)) the$column_formats$Parameter@formatter else column_formats$Parameter@formatter
  labels <- rep(formatter(outcome_names), vapply(tables, nrow, integer(1)))
  d <- add_stratum_rows(dplyr::bind_rows(tables), labels)
  note$model_sentences <- "Univariate analyses of variance of each outcome."
  attr(d, "apa_note") <- note
  as_apa7_tbl(d)
}

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.