R/model_contrast_table.R

Defines functions model_contrast_table

Documented in model_contrast_table

#' Summarize Model Variables, Families, and Contrast Matrices
#'
#' @description
#' `model_contrast_table()` extracts model-level and variable-level information
#' from a fitted model object.
#'
#' It reports the model class, family and link function when available, number
#' of variables, dependent variable, predictors, interactions, random-effect
#' grouping variables, variable types, number of factor levels, and contrast
#' matrix types for categorical variables.
#'
#' The function is designed to work with fitted models supported by the
#' package's internal model-extraction infrastructure, including models fitted
#' with [stats::lm()], [stats::glm()], [lme4::lmer()],
#' [lme4::glmer()], [nlme::lme()], and [glmmTMB::glmmTMB()].
#'
#' @param model A fitted model object.
#' @param type Character string indicating which output should be returned.
#'   Available options are `"all"`, `"summary"`, `"x&y"`, `"x"`, and `"y"`.
#'
#' @details
#' Variables found in the model frame are reported in the variable-level
#' summary. In mixed-effects models, grouping variables used in the random
#' structure may therefore also appear among the predictors.
#'
#' To avoid interpreting these variables as fixed effects only, the model-level
#' summary includes a separate `"Random Effects"` row listing the grouping
#' variables used in the random-effects structure.
#'
#' The variable-level summary also contains a `Random_Effect` column that
#' indicates whether each variable is used as a random-effect grouping
#' variable.
#'
#' The function identifies the following contrast matrix types:
#' \itemize{
#'   \item `"Sum"`: sum-to-zero contrasts generated by [stats::contr.sum()].
#'   \item `"Treatment"`: treatment contrasts generated by [stats::contr.treatment()].
#'   \item `"Polynomial"`: polynomial contrasts generated by [stats::contr.poly()],
#'     with equally spaced or user-supplied `scores`.
#'   \item `"Helmert"`: Helmert contrasts generated by [stats::contr.helmert()].
#'   \item `"Sliding Differences"`: sliding-difference contrasts generated by
#'     [MASS::contr.sdif()].
#'   \item `"Reverse Helmert"`: reverse Helmert contrasts generated by [reverse_helmert()].
#'   \item `"Custom"`: any other user-defined contrast matrix.
#' }
#'
#' Matrices that do not coincide with one of these generators are classified
#' from the structure of their hypothesis matrix, the inverse of the coding
#' matrix with an intercept column. Treatment contrasts are therefore
#' recognized with any reference level, sum contrasts with any omitted level,
#' and all types after rescaling of their columns. The same classification is
#' used by [contrasts_onepred()] and [moplot_onepred()].
#'
#' @return Depending on `type`, either a list of two data frames or a single data frame.
#'
#' @examples
#' set.seed(1234)
#' dat <- data.frame(
#'   group = factor(rep(c("A", "B", "C"), each = 20)),
#'   y = rnorm(60)
#' )
#' contrasts(dat$group) <- stats::contr.helmert(3)
#' mod <- stats::lm(y ~ group, data = dat)
#' model_contrast_table(mod)
#'
#' @importFrom stats formula terms contrasts contr.treatment contr.sum contr.poly contr.helmert na.omit
#' @export
model_contrast_table <- function(model,
                               type = c(
                                 "all",
                                 "summary",
                                 "x&y",
                                 "x",
                                 "y"
                               )) {

  # ============================================================
  # 1. ARGUMENT MATCHING AND MODEL VALIDATION
  # ============================================================

  type <- match.arg(type)

  if (!.is_supported_model(model)) {
    stop(
      paste0(
        "Unsupported model class. Supported model classes include ",
        "lm, glm, lme4::lmer/glmer, lmerTest::lmer, nlme::lme, ",
        "and glmmTMB."
      ),
      call. = FALSE
    )
  }

  # ============================================================
  # 2. MODEL-LEVEL INFORMATION
  # ============================================================

  model_class <- .model_class_label(model)
  model_family <- .family_link_label(model)

  fixed_formula <- .extract_fixed_formula(model)
  terms_object <- stats::terms(fixed_formula)
  model_frame <- .extract_model_frame(model)

  random_effects <- .extract_random_effects(model)

  random_effects_label <- if (length(random_effects) == 0L) {
    NA_character_
  } else {
    paste(random_effects, collapse = ", ")
  }

  # ============================================================
  # 3. IDENTIFY RESPONSE AND PREDICTOR VARIABLES
  # ============================================================

  # Robust extraction of response variable name directly from terms/model frame
  response_idx <- attr(terms_object, "response")
  if (is.null(response_idx) || response_idx == 0L) {
    response_variables <- character(0L)
  } else {
    # Extract response variable names safely handling cbind() or transformations
    raw_response <- attr(terms_object, "variables")[[response_idx + 1L]]
    response_variables <- all.vars(raw_response)
  }

  variable_names <- names(model_frame)

  # Ensure matching against actual column names in model_frame
  matched_response <- variable_names[variable_names %in% response_variables |
                                       variable_names %in% as.character(raw_response)]

  if (length(matched_response) == 0L && length(response_variables) > 0L) {
    # Fallback to first column if formula uses complex transformation
    matched_response <- variable_names[1L]
  }

  predictor_variables <- setdiff(variable_names, matched_response)
  predictor_terms <- attr(terms_object, "term.labels")

  number_total_variables <- length(variable_names)
  number_dependent_variables <- length(matched_response)
  number_predictors <- length(predictor_variables)
  number_interactions <- sum(grepl(":", predictor_terms, fixed = TRUE))

  # ============================================================
  # 4. VARIABLE INFORMATION HELPERS
  # ============================================================

  get_variable_type <- function(variable) {
    class(variable)[1L]
  }

  get_variable_levels <- function(variable) {
    if (is.factor(variable)) {
      return(as.character(nlevels(variable)))
    }
    "Numeric"
  }

  detect_contrast <- function(variable) {
    if (!is.factor(variable)) {
      return(NA_character_)
    }

    contrast_matrix <- stats::contrasts(variable)

    if (is.null(contrast_matrix)) {
      return(NA_character_)
    }

    # Shared with contrasts_onepred(), so that both functions always
    # agree on the contrast type.
    .classify_contrast(contrast_matrix)$type
  }

  # ============================================================
  # 5. VARIABLE-LEVEL SUMMARY
  # ============================================================

  variable_types <- vapply(
    model_frame[variable_names],
    get_variable_type,
    character(1L)
  )

  variable_levels <- vapply(
    model_frame[variable_names],
    get_variable_levels,
    character(1L)
  )

  contrast_types <- vapply(
    model_frame[variable_names],
    detect_contrast,
    character(1L)
  )

  variable_table <- data.frame(
    Variable = variable_names,
    Role = ifelse(
      variable_names %in% matched_response,
      "Dependent",
      "Predictor"
    ),
    Type = unname(variable_types),
    Levels = unname(variable_levels),
    Contrast_Matrix_Type = unname(contrast_types),
    Random_Effect = variable_names %in% random_effects,
    stringsAsFactors = FALSE,
    row.names = NULL
  )

  # ============================================================
  # 6. MODEL-LEVEL CONTRAST SUMMARY
  # ============================================================

  predictor_contrast_types <- contrast_types[predictor_variables]
  contrast_summary <- unique(stats::na.omit(predictor_contrast_types))

  contrast_summary <- if (length(contrast_summary) == 0L) {
    NA_character_
  } else {
    paste(contrast_summary, collapse = ", ")
  }

  # ============================================================
  # 7. SAFE VARIABLE LOOKUPS
  # ============================================================

  response_types <- variable_types[matched_response[matched_response %in% names(variable_types)]]
  response_levels <- variable_levels[matched_response[matched_response %in% names(variable_levels)]]

  predictor_types <- variable_types[predictor_variables[predictor_variables %in% names(variable_types)]]
  predictor_levels <- variable_levels[predictor_variables[predictor_variables %in% names(variable_levels)]]

  collapse_or_na <- function(values) {
    values <- unname(values)
    if (length(values) == 0L) {
      return(NA_character_)
    }
    paste(values, collapse = ", ")
  }

  # ============================================================
  # 8. MODEL-LEVEL SUMMARY TABLE
  # ============================================================

  summary_table <- data.frame(
    Metric = c(
      "Model Class",
      "Family / Link",
      "Total Variables",
      "Dependent Variables",
      "Predictors",
      "Interactions",
      "Random Effects",
      "Dependent Variable Name",
      "Dependent Variable Type",
      "Dependent Variable Levels",
      "Predictor Names",
      "Predictor Types",
      "Predictor Levels",
      "Contrast Matrix Types"
    ),
    Value = c(
      model_class,
      model_family,
      as.character(number_total_variables),
      as.character(number_dependent_variables),
      as.character(number_predictors),
      as.character(number_interactions),
      random_effects_label,
      collapse_or_na(matched_response),
      collapse_or_na(response_types),
      collapse_or_na(response_levels),
      collapse_or_na(predictor_variables),
      collapse_or_na(predictor_types),
      collapse_or_na(predictor_levels),
      contrast_summary
    ),
    stringsAsFactors = FALSE,
    row.names = NULL
  )

  # ============================================================
  # 9. ASSIGN OUTPUT CLASSES AND RETURN REQUESTED OUTPUT
  # ============================================================

  if (type == "all") {
    output <- list(
      `Model-Level Summary` = summary_table,
      `Variable-Level Summary` = variable_table
    )
    class(output) <- c("model_contrast_table", class(output))
    return(output)
  }

  if (type == "summary") {
    class(summary_table) <- c("model_contrast_summary", class(summary_table))
    return(summary_table)
  }

  if (type == "x&y") {
    class(variable_table) <- c("model_contrast_variables", class(variable_table))
    return(variable_table)
  }

  if (type == "y") {
    output <- variable_table[variable_table$Role == "Dependent", , drop = FALSE]
    class(output) <- c("model_contrast_variables", class(output))
    return(output)
  }

  output <- variable_table[variable_table$Role == "Predictor", , drop = FALSE]
  class(output) <- c("model_contrast_variables", class(output))
  output
}

Try the MoPlot package in your browser

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

MoPlot documentation built on Nov. 25, 2026, 5:10 p.m.