R/mlm.R

Defines functions mlm_performance apa_performance.mlm mlm_note_sentences stop_multivariate_list mlm_std_coefficients apa_parameters.mlm

Documented in apa_parameters.mlm apa_performance.mlm

# Coefficient tables of multivariate linear models ----

#' @param outcomes for multivariate linear models (`lm(cbind(y1, y2) ~ x)`),
#'   where each outcome's coefficients go: `"rows"` (default), under a heading
#'   row for each outcome, or `"columns"`, side by side under a column spanner
#'   for each outcome.
#' @details
#' For multivariate linear models, fit with [stats::lm()] and several outcomes
#' (`lm(cbind(y1, y2) ~ x)`, class `mlm`), each outcome's coefficients are
#' shown as for an `lm` model, under a heading row for each outcome (or side
#' by side, with `outcomes = "columns"`). The coefficients and their tests
#' are those of a separate regression of each outcome on the same
#' predictors, so they do not take the correlations among the outcomes into
#' account. For multivariate tests of each predictor, use [apa_anova()].
#' Lists of multivariate models are not supported yet.
#' @export
#' @rdname apa_parameters
#' @examples
#' # Multivariate regression: the coefficients of each outcome
#' fit_mlm <- lm(cbind(mpg, qsec) ~ wt + hp, data = mtcars)
#' apa_parameters(fit_mlm)
#' apa_parameters(fit_mlm, outcomes = "columns")
apa_parameters.mlm <- function(
  fit,
  predictor_parameters = c(
    "Parameter",
    "Coefficient",
    "SE",
    "Std_Coefficient",
    "t",
    "df_error",
    "p"
  ),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  outcomes = c("rows", "columns"),
  ...
) {
  outcomes <- match.arg(outcomes)
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL

  d_b <- parameters::model_parameters(fit, ...) |>
    tibble::as_tibble()
  if ("Std_Coefficient" %in% predictor_parameters) {
    d_b <- dplyr::left_join(d_b, mlm_std_coefficients(fit), by = c("Parameter", "Response"))
  }
  name_formatter <- column_formats$Parameter@formatter
  d_b$Parameter <- name_formatter(pretty_parameter_names(fit, d_b$Parameter))

  responses <- unique(d_b$Response)
  labels <- name_formatter(responses)
  note <- list(
    vcov = describe_vcov(list(...)$vcov),
    model_sentences = mlm_note_sentences(labels, stats::nobs(fit))
  )
  # Names were formatted above
  column_formats$Parameter@formatter <- \(x, ...) x

  if (outcomes == "rows") {
    pieces <- purrr::map(seq_along(responses), \(i) {
      block <- d_b[d_b$Response == responses[i], ]
      block$Response <- NULL
      block$Parameter <- paste0("\u2003", block$Parameter)
      dplyr::bind_rows(tibble::tibble(Parameter = labels[i]), block)
    })
    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 outcome, joined under column spanners
  tables <- purrr::map(responses, \(r) {
    block <- d_b[d_b$Response == r, ]
    block$Response <- NULL
    format_apa_parameters(
      block,
      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
  labels_formatted(as_apa7_tbl(out))
}

# Standardized coefficients ----

#' Standardized coefficients of each outcome, as
#' `parameters::standardise_parameters(method = "basic")` computes them for
#' an `lm` model of that outcome (it refuses multivariate models): the
#' coefficient times the *SD* of its column of the model matrix, divided by
#' the *SD* of the outcome
#' @keywords internal
#' @noRd
mlm_std_coefficients <- function(fit) {
  x_sd <- apply(stats::model.matrix(fit), 2, stats::sd)
  y <- stats::fitted(fit) + stats::residuals(fit)
  y_sd <- apply(y, 2, stats::sd)
  b <- stats::coef(fit)
  std <- sweep(b * x_sd[rownames(b)], 2, y_sd[colnames(b)], "/")
  tibble::tibble(
    Parameter = rep(rownames(b), times = ncol(b)),
    Response = rep(colnames(b), each = nrow(b)),
    Std_Coefficient = as.vector(std)
  )
}

# Lists of multivariate models ----

#' Stop for lists of multivariate models, which are not supported yet
#' @param models list of models
#' @keywords internal
#' @noRd
stop_multivariate_list <- function(models, call = rlang::caller_env()) {
  if (any(purrr::map_lgl(models, \(m) inherits(m, "mlm")))) {
    cli::cli_abort(
      c(
        "Lists of multivariate models ({.cls mlm}) are not supported yet.",
        i = "Use {.fn apa_anova} for multivariate tests of each model's effects, and {.fn apa_parameters} for each model's coefficients."
      ),
      call = call
    )
  }
}

# Note sentences ----

#' "Coefficients are from separate regressions of A, B, and C on the same
#' predictors, ... *N* = 66."
#' @keywords internal
#' @noRd
mlm_note_sentences <- function(outcomes, n) {
  c(
    paste0(
      "Coefficients are from separate regressions of ",
      and_list(outcomes),
      " on the same predictors, so their tests do not take the correlations among the outcomes into account."
    ),
    n_sentence(n)
  )
}

# Fit statistics of each outcome ----

#' @details
#' For multivariate linear models (class `mlm`), each outcome gets a row
#' (labeled in an Outcome column) with its *R*^2^, adjusted *R*^2^, and
#' residual *SD* (`Sigma`), computed from [stats::summary.lm()] for each
#' outcome. `"all"` adds the overall *F* test of each outcome's regression.
#' @export
#' @rdname apa_performance
apa_performance.mlm <- function(
  fit,
  metrics = c("R2", "R2_adjusted", "Sigma"),
  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", "F", "df", "df_error", "p")
  }
  d <- mlm_performance(fit)
  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$"
  }
  out <- format_performance(d, metrics, column_formats)
  outcome <- column_formats$Parameter@formatter(colnames(stats::residuals(fit)))
  tibble::add_column(out, Outcome = outcome, .before = 1) |>
    as_apa7_tbl()
}

#' Fit statistics of each outcome of a multivariate linear model
#' @keywords internal
#' @noRd
mlm_performance <- function(fit) {
  rows <- purrr::map(summary(fit), \(s) {
    f <- s$fstatistic
    tibble::tibble(
      R2 = s$r.squared,
      R2_adjusted = s$adj.r.squared,
      Sigma = s$sigma,
      F = if (is.null(f)) NA_real_ else unname(f["value"]),
      df = if (is.null(f)) NA_real_ else unname(f["numdf"]),
      df_error = if (is.null(f)) NA_real_ else unname(f["dendf"]),
      p = if (is.null(f)) NA_real_ else stats::pf(f["value"], f["numdf"], f["dendf"], lower.tail = FALSE)
    )
  })
  dplyr::bind_rows(rows)
}

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.