R/contrast_hypotheses.R

Defines functions .check_hypothesis_identity .describe_level_set .check_declared_hypotheses .describe_hypothesis_row .format_scale_factor .contrast_hypotheses .format_weighted_group .classify_contrast .is_positive_multiple .hypothesis_matrix

# ============================================================
# CONTRAST HYPOTHESES
# ============================================================
#
# A contrast (coding) matrix C describes how a factor is coded in
# the model. It does not, in general, describe what the estimated
# coefficients compare. For a factor with k levels and k - 1
# contrasts, the cell means satisfy
#
#   mu = X_C beta,   X_C = [1, C],
#
# so that
#
#   beta = H mu,     H = X_C^{-1}.
#
# Row j + 1 of H (the hypothesis row h_j) states the combination
# of cell means estimated by the j-th contrast coefficient. These
# helpers make H the single source of truth for interpreting
# contrasts. The contrast type is used only to choose a readable
# presentation, which must reconstruct h_j exactly.
#
# Every non-intercept row of H sums to zero, because H %*% 1 is
# the first unit vector. Each row can therefore be written as
#
#   h_j = s_j (w_plus - w_minus),
#
# where w_plus and w_minus are weight vectors summing to one and
# s_j > 0 is a scale factor. Then
#
#   beta_j = s_j (sum(w_plus * mu) - sum(w_minus * mu)).
# ============================================================


#' Hypothesis matrix implied by a contrast matrix
#'
#' Internal helper. Inverts `[1, C]` to obtain the combination of cell
#' means estimated by each contrast coefficient.
#'
#' @param contrast_matrix A k x (k - 1) contrast (coding) matrix.
#' @param tolerance Relative tolerance below which weights are set to zero.
#'
#' @return A (k - 1) x k matrix whose rows are the hypothesis rows of the
#'   contrast coefficients and whose columns correspond to factor levels.
#'
#' @keywords internal
#' @noRd
.hypothesis_matrix <- function(contrast_matrix,
                               tolerance = 1e-8) {

  contrast_matrix <- as.matrix(contrast_matrix)

  if (!is.numeric(contrast_matrix) ||
      anyNA(contrast_matrix)) {

    stop(
      "The contrast matrix must be numeric and must not contain missing values.",
      call. = FALSE
    )
  }

  number_levels <- nrow(contrast_matrix)

  if (ncol(contrast_matrix) != number_levels - 1L) {

    stop(
      paste0(
        "The contrast matrix must have k - 1 = ",
        number_levels - 1L,
        " columns for a factor with ",
        number_levels,
        " levels; it has ",
        ncol(contrast_matrix),
        "."
      ),
      call. = FALSE
    )
  }

  coding_matrix <- cbind(1, unname(contrast_matrix))

  if (qr(coding_matrix)$rank < number_levels) {

    stop(
      paste0(
        "The contrast coding is not full rank: the intercept and the ",
        "contrast columns are linearly dependent, so the coefficients ",
        "do not identify unique comparisons between levels."
      ),
      call. = FALSE
    )
  }

  hypothesis_matrix <- solve(coding_matrix)[-1L, , drop = FALSE]

  # solve() leaves numerical residues (e.g. 1e-17) where the exact
  # weight is zero. They would otherwise add spurious levels to the
  # positive or negative side of a contrast.
  hypothesis_matrix[abs(hypothesis_matrix) < tolerance * max(abs(hypothesis_matrix))] <- 0

  level_names <- rownames(contrast_matrix)

  if (is.null(level_names)) {
    level_names <- as.character(seq_len(number_levels))
  }

  contrast_names <- colnames(contrast_matrix)

  if (is.null(contrast_names)) {
    contrast_names <- as.character(seq_len(number_levels - 1L))
  }

  dimnames(hypothesis_matrix) <- list(contrast_names, level_names)

  hypothesis_matrix
}


# ============================================================
# CONTRAST CLASSIFICATION
# ============================================================

#' Is a vector a positive multiple of a target pattern?
#'
#' @keywords internal
#' @noRd
.is_positive_multiple <- function(values,
                                  pattern,
                                  tolerance = 1e-8) {

  scale <- sum(values * pattern) / sum(pattern * pattern)

  scale > 0 &&
    max(abs(values - scale * pattern)) <= tolerance * max(abs(values))
}


#' Classify a contrast matrix
#'
#' Internal helper shared by the package functions. Canonical matrices
#' generated by the standard contrast functions are recognized first, which
#' also resolves the ambiguities that arise with two levels. Other matrices
#' are classified from the structure of their hypothesis rows, so that, for
#' example, treatment contrasts with any reference level and sum contrasts
#' with any omitted level are recognized regardless of how they were coded.
#'
#' @param contrast_matrix A k x (k - 1) contrast matrix.
#' @param hypothesis_matrix Optional hypothesis matrix returned by
#'   `.hypothesis_matrix()`.
#'
#' @return A list with elements `type` (one of `"Treatment"`, `"Sum"`,
#'   `"Polynomial"`, `"Helmert"`, `"Reverse Helmert"`,
#'   `"Sliding Differences"`, `"Custom"`) and `reference` (the index of the
#'   reference level for treatment contrasts, otherwise `NA`).
#'
#' @keywords internal
#' @noRd
.classify_contrast <- function(contrast_matrix,
                               hypothesis_matrix = NULL) {

  contrast_matrix <- unname(as.matrix(contrast_matrix))
  number_levels <- nrow(contrast_matrix)

  same_matrix <- function(first, second) {
    identical(dim(first), dim(unname(second))) &&
      isTRUE(all.equal(first, unname(second), check.attributes = FALSE))
  }

  result <- function(type, reference = NA_integer_) {
    list(type = type, reference = reference)
  }

  # ----------------------------------------------------------
  # CANONICAL MATRICES
  # ----------------------------------------------------------

  for (reference in seq_len(number_levels)) {
    if (same_matrix(contrast_matrix, stats::contr.treatment(number_levels, base = reference))) {
      return(result("Treatment", reference))
    }
  }

  canonical_matrices <- list(
    "Sum" = stats::contr.sum(number_levels),
    "Polynomial" = stats::contr.poly(number_levels),
    "Helmert" = stats::contr.helmert(number_levels),
    "Reverse Helmert" = reverse_helmert(number_levels),
    "Sliding Differences" = MASS::contr.sdif(number_levels)
  )

  for (contrast_type in names(canonical_matrices)) {
    if (same_matrix(contrast_matrix, canonical_matrices[[contrast_type]])) {
      return(result(contrast_type))
    }
  }

  # Polynomial contrasts with unequally spaced scores, as generated by
  # contr.poly(k, scores = s). The linear column is proportional to the
  # centered scores, and contr.poly() is invariant to their location and
  # scale, so the column itself recovers the matrix.
  if (number_levels >= 3L &&
      ncol(contrast_matrix) == number_levels - 1L &&
      !anyDuplicated(signif(contrast_matrix[, 1L], 10L))) {

    scored_polynomial <- tryCatch(
      stats::contr.poly(number_levels, scores = contrast_matrix[, 1L]),
      error = function(e) NULL
    )

    if (!is.null(scored_polynomial) && same_matrix(contrast_matrix, scored_polynomial)) {
      return(result("Polynomial"))
    }
  }

  # ----------------------------------------------------------
  # STRUCTURE OF THE HYPOTHESIS ROWS
  # ----------------------------------------------------------

  if (is.null(hypothesis_matrix)) {

    hypothesis_matrix <- tryCatch(
      .hypothesis_matrix(contrast_matrix),
      error = function(e) NULL
    )
  }

  if (is.null(hypothesis_matrix)) {
    return(result("Custom"))
  }

  hypothesis_matrix <- unname(hypothesis_matrix)
  number_contrasts <- nrow(hypothesis_matrix)

  unit_vector <- function(index) {
    replace(numeric(number_levels), index, 1)
  }

  rows_match <- function(patterns) {
    all(vapply(
      seq_len(number_contrasts),
      function(row_index) {
        .is_positive_multiple(hypothesis_matrix[row_index, ], patterns[[row_index]])
      },
      logical(1)
    ))
  }

  # Treatment: every row compares one level with a common reference.
  # The rows may appear in any order.
  reference_candidates <- which(apply(hypothesis_matrix < 0, 2L, all))

  for (reference in reference_candidates) {

    focal_levels <- apply(
      hypothesis_matrix,
      1L,
      function(row) {
        positive_levels <- which(row > 0)
        if (length(positive_levels) == 1L) positive_levels else NA_integer_
      }
    )

    if (!anyNA(focal_levels) &&
        setequal(focal_levels, setdiff(seq_len(number_levels), reference)) &&
        rows_match(lapply(focal_levels, function(level) unit_vector(level) - unit_vector(reference)))) {

      return(result("Treatment", reference))
    }
  }

  # Sum: every row compares one level with the unweighted grand mean.
  # Any level may be omitted and the rows may appear in any order.
  focal_levels <- apply(hypothesis_matrix, 1L, which.max)

  if (!anyDuplicated(focal_levels) &&
      rows_match(lapply(focal_levels, function(level) unit_vector(level) - 1 / number_levels))) {

    return(result("Sum"))
  }

  # Ordered systems: the row order is part of the definition.
  helmert_patterns <- lapply(
    seq_len(number_contrasts),
    function(j) unit_vector(j + 1L) - c(rep(1 / j, j), numeric(number_levels - j))
  )

  if (rows_match(helmert_patterns)) {
    return(result("Helmert"))
  }

  reverse_helmert_patterns <- lapply(
    seq_len(number_contrasts),
    function(j) unit_vector(j) - c(numeric(j), rep(1 / (number_levels - j), number_levels - j))
  )

  if (rows_match(reverse_helmert_patterns)) {
    return(result("Reverse Helmert"))
  }

  sliding_patterns <- lapply(
    seq_len(number_contrasts),
    function(j) unit_vector(j + 1L) - unit_vector(j)
  )

  if (rows_match(sliding_patterns)) {
    return(result("Sliding Differences"))
  }

  result("Custom")
}


# ============================================================
# DECOMPOSITION OF THE HYPOTHESIS ROWS
# ============================================================

#' Format a weighted group of factor levels
#'
#' @param weights Named numeric vector of non-negative weights summing to one.
#' @param digits Number of decimal places used for unequal weights.
#'
#' @return A character string: the level name for a single level,
#'   `"Mean(A, B)"` for equal weights, `"W(A .20, C .80)"` otherwise.
#'
#' @keywords internal
#' @noRd
.format_weighted_group <- function(weights,
                                   digits = 2L) {

  weights <- weights[weights > 0]

  if (length(weights) == 1L) {
    return(names(weights))
  }

  if (isTRUE(all.equal(unname(weights), rep(1 / length(weights), length(weights))))) {

    return(
      paste0("Mean(", paste(names(weights), collapse = ", "), ")")
    )
  }

  # Weights are below one within a group of two or more levels, so
  # the leading zero is dropped: 0.20 -> .20.
  formatted_weights <- sub("^0\\.", ".", formatC(weights, format = "f", digits = digits))

  paste0(
    "W(",
    paste(names(weights), formatted_weights, collapse = ", "),
    ")"
  )
}


#' Decompose contrast coefficients into weighted level comparisons
#'
#' Internal helper. For each contrast coefficient, returns the weighted
#' groups of levels on the positive and negative side and the scale factor
#' such that `h_j = scale * (positive_weights - negative_weights)`.
#'
#' Sum contrasts are presented as one level versus the unweighted Grand Mean
#' of all levels (overlapping groups). All other types use the unique split
#' of the hypothesis row into disjoint positive and negative groups.
#' Polynomial contrasts are classified but not decomposed, because a split
#' into positive and negative groups is not meaningful for them.
#'
#' For custom contrasts, the levels suggested by the signs of the coding
#' column are compared with the levels actually involved in the hypothesis.
#' When they differ, the comparison is flagged as divergent and a note
#' describing the estimated comparison is returned.
#'
#' @param contrast_matrix A k x (k - 1) contrast matrix with levels as row
#'   names.
#' @param level_names Optional character vector of factor levels; defaults
#'   to the row names of `contrast_matrix`.
#' @param tolerance Relative tolerance used to identify zero weights.
#'
#' @return A list with elements `type`, `reference`, `hypothesis_matrix`,
#'   and `contrasts`. The last is a list with one element per contrast
#'   containing `positive_weights`, `negative_weights` (named numeric
#'   vectors over all levels), `scale`, `positive_label`, `negative_label`,
#'   `overlapping`, `divergent`, and `note`. For polynomial contrasts,
#'   `contrasts` is `NULL`.
#'
#' @keywords internal
#' @noRd
.contrast_hypotheses <- function(contrast_matrix,
                                 level_names = rownames(contrast_matrix),
                                 tolerance = 1e-8) {

  contrast_matrix <- as.matrix(contrast_matrix)

  if (is.null(level_names)) {
    level_names <- as.character(seq_len(nrow(contrast_matrix)))
  }

  if (length(level_names) != nrow(contrast_matrix)) {

    stop(
      "The number of level names must equal the number of rows of the contrast matrix.",
      call. = FALSE
    )
  }

  rownames(contrast_matrix) <- level_names

  hypothesis_matrix <- .hypothesis_matrix(contrast_matrix, tolerance = tolerance)

  classification <- .classify_contrast(contrast_matrix, hypothesis_matrix)

  output <- list(
    type = classification$type,
    reference = classification$reference,
    hypothesis_matrix = hypothesis_matrix,
    contrasts = NULL
  )

  if (identical(classification$type, "Polynomial")) {
    return(output)
  }

  number_levels <- length(level_names)

  output$contrasts <- lapply(
    seq_len(nrow(hypothesis_matrix)),
    function(contrast_index) {

      hypothesis_row <- hypothesis_matrix[contrast_index, ]

      if (identical(classification$type, "Sum")) {

        # h_j = s (e_i - 1/k): level i versus the Grand Mean.
        focal_level <- which.max(hypothesis_row)

        # The focal weight is s (1 - 1/k).
        scale <- hypothesis_row[[focal_level]] * number_levels / (number_levels - 1)

        positive_weights <- stats::setNames(numeric(number_levels), level_names)
        positive_weights[focal_level] <- 1

        negative_weights <- stats::setNames(rep(1 / number_levels, number_levels), level_names)

        positive_label <- level_names[focal_level]
        negative_label <- "Grand Mean"
        overlapping <- TRUE

      } else {

        scale <- sum(hypothesis_row[hypothesis_row > 0])

        positive_weights <- stats::setNames(pmax(hypothesis_row, 0) / scale, level_names)
        negative_weights <- stats::setNames(pmax(-hypothesis_row, 0) / scale, level_names)

        positive_label <- .format_weighted_group(positive_weights)
        negative_label <- .format_weighted_group(negative_weights)
        overlapping <- FALSE
      }

      # The presentation must reconstruct the hypothesis row exactly.
      reconstructed_row <- scale * (positive_weights - negative_weights)

      if (max(abs(reconstructed_row - hypothesis_row)) > tolerance * max(abs(hypothesis_row))) {

        stop(
          paste0(
            "Internal error: the decomposition of contrast ",
            contrast_index,
            " does not reconstruct its hypothesis row."
          ),
          call. = FALSE
        )
      }

      # Compare the levels suggested by the coding column with the
      # levels actually involved in the hypothesis. Only custom
      # matrices are checked: for the recognized types the coding
      # signs are known not to describe the comparison (e.g. treatment
      # columns contain no negative weight) and the presentation is
      # documented for each type.
      divergent <- FALSE
      note <- NA_character_

      if (identical(classification$type, "Custom")) {

        coding_column <- contrast_matrix[, contrast_index]

        suggested_positive <- level_names[coding_column > 0]
        suggested_negative <- level_names[coding_column < 0]

        divergent <- !setequal(suggested_positive, level_names[positive_weights > 0]) ||
          !setequal(suggested_negative, level_names[negative_weights > 0])

        if (divergent) {

          # The package cannot know the intended comparisons: the
          # note reports that the signs of the coding column do not
          # describe the estimated comparison, which is expected for a
          # coding derived from a hypothesis matrix.
          note <- paste0(
            "Contrast_", contrast_index, ": the signs of the coding column suggest ",
            .describe_level_set(suggested_positive), " vs ",
            .describe_level_set(suggested_negative),
            ", whereas the coefficient estimates ",
            .describe_hypothesis_row(hypothesis_row, level_names),
            ". This is expected when the coding was derived from a hypothesis ",
            "matrix (for example with MASS::ginv() or hypr)."
          )
        }
      }

      list(
        positive_weights = positive_weights,
        negative_weights = negative_weights,
        scale = scale,
        positive_label = positive_label,
        negative_label = negative_label,
        overlapping = overlapping,
        divergent = divergent,
        note = note
      )
    }
  )

  names(output$contrasts) <- rownames(hypothesis_matrix)

  output
}


#' Format scale factors for captions
#'
#' Simple fractions such as 1/3 are shown as fractions; other values are
#' shown with three significant digits.
#'
#' @keywords internal
#' @noRd
.format_scale_factor <- function(scale_factors) {

  vapply(
    scale_factors,
    function(value) {

      fraction <- as.character(MASS::fractions(value, max.denominator = 20L))

      parts <- as.numeric(strsplit(fraction, "/", fixed = TRUE)[[1L]])

      approximation <- if (length(parts) == 2L) parts[1L] / parts[2L] else parts[1L]

      if (abs(approximation - value) < 1e-8) {
        return(fraction)
      }

      formatC(value, format = "fg", digits = 3)
    },
    character(1)
  )
}


#' Describe a weight row as a comparison between two groups of levels
#'
#' Internal helper. Writes a row of weights summing to zero as
#' `s x [positive group - negative group]`, or as
#' `positive group - negative group` when the scale factor is one.
#'
#' @param row Numeric weights, one per level.
#' @param level_names Factor levels.
#'
#' @return A character string.
#'
#' @keywords internal
#' @noRd
.describe_hypothesis_row <- function(row,
                                     level_names) {

  row <- stats::setNames(as.numeric(row), level_names)

  row[abs(row) < 1e-10 * max(abs(row))] <- 0

  scale <- sum(row[row > 0])

  if (scale <= 0) {
    return("no comparison")
  }

  comparison <- paste0(
    .format_weighted_group(pmax(row, 0) / scale),
    " - ",
    .format_weighted_group(pmax(-row, 0) / scale)
  )

  if (abs(scale - 1) < 1e-8) {
    return(comparison)
  }

  paste0(.format_scale_factor(scale), " x [", comparison, "]")
}


#' Check declared hypotheses against the estimated comparisons
#'
#' Internal helper. The package cannot know which comparisons the analyst
#' intended; `hypotheses` declares them as a matrix with one row per contrast
#' coefficient and one column per factor level, as the rows of a hypothesis
#' matrix. Each declared row is compared with the corresponding row of the
#' hypothesis matrix implied by the coding. The coefficient estimates the
#' declared hypothesis when the two rows are proportional: exactly (ratio 1),
#' up to a positive factor, or with reversed sign.
#'
#' @param declared Numeric matrix (or vector for a two-level factor) of
#'   declared hypotheses. Column names, when present, must be the factor
#'   levels; row names label the hypotheses.
#' @param hypothesis_matrix Hypothesis matrix implied by the coding, without
#'   the intercept row.
#' @param level_names Factor levels.
#' @param tolerance Relative tolerance for proportionality.
#'
#' @return A list with `table`, a data frame with one row per contrast
#'   (`Contrast`, `Hypothesis`, `Declared`, `Estimated`, `Status`, `Ratio`),
#'   and `messages`, one message per contrast.
#'
#' @keywords internal
#' @noRd
.check_declared_hypotheses <- function(declared,
                                       hypothesis_matrix,
                                       level_names,
                                       tolerance = 1e-6) {

  number_contrasts <- nrow(hypothesis_matrix)
  number_levels <- length(level_names)

  if (is.null(dim(declared))) {
    declared <- matrix(declared, nrow = 1L, dimnames = list(NULL, names(declared)))
  }

  declared <- as.matrix(declared)

  if (!is.numeric(declared) ||
      anyNA(declared) ||
      ncol(declared) != number_levels ||
      nrow(declared) != number_contrasts) {

    stop(
      paste0(
        "`hypotheses` must be a numeric matrix with one row per coefficient ",
        "of the predictor (", number_contrasts, ") and one column per level (",
        number_levels, ": ", paste(level_names, collapse = ", "), ")."
      ),
      call. = FALSE
    )
  }

  if (!is.null(colnames(declared))) {

    if (!setequal(colnames(declared), level_names)) {

      stop(
        paste0(
          "The column names of `hypotheses` must be the levels of the ",
          "predictor: ", paste(level_names, collapse = ", "), "."
        ),
        call. = FALSE
      )
    }

    declared <- declared[, level_names, drop = FALSE]
  }

  if (any(abs(rowSums(declared)) > tolerance * pmax(1, rowSums(abs(declared))))) {

    stop(
      paste0(
        "Each row of `hypotheses` must define a comparison, with weights ",
        "summing to zero (for example c(-1, 0.5, 0.5))."
      ),
      call. = FALSE
    )
  }

  hypothesis_labels <- rownames(declared)

  if (is.null(hypothesis_labels)) {
    hypothesis_labels <- rep("", number_contrasts)
  }

  unnamed <- is.na(hypothesis_labels) | !nzchar(hypothesis_labels)

  hypothesis_labels[unnamed] <- paste0("H", which(unnamed))

  rows <- lapply(
    seq_len(number_contrasts),
    function(index) {

      declared_row <- declared[index, ]
      estimated_row <- hypothesis_matrix[index, ]

      ratio <- sum(estimated_row * declared_row) / sum(declared_row^2)

      proportional <- is.finite(ratio) &&
        max(abs(estimated_row - ratio * declared_row)) <=
        tolerance * max(abs(estimated_row))

      status <- if (!proportional) {
        "differs"
      } else if (ratio < 0) {
        "reversed"
      } else if (abs(ratio - 1) < tolerance) {
        "matches"
      } else {
        "rescaled"
      }

      declared_text <- .describe_hypothesis_row(declared_row, level_names)
      estimated_text <- .describe_hypothesis_row(estimated_row, level_names)

      message_text <- switch(
        status,
        "matches" = paste0(
          "Contrast_", index, " estimates the declared hypothesis '",
          hypothesis_labels[index], "': ", declared_text, "."
        ),
        "rescaled" = paste0(
          "Contrast_", index, " estimates the declared hypothesis '",
          hypothesis_labels[index], "' (", declared_text, ") multiplied by ",
          .format_scale_factor(ratio), "."
        ),
        "reversed" = paste0(
          "Contrast_", index, " estimates the declared hypothesis '",
          hypothesis_labels[index], "' (", declared_text, ") with reversed sign",
          if (abs(ratio + 1) > tolerance) paste0(", multiplied by ", .format_scale_factor(-ratio)),
          ": it estimates ", estimated_text, "."
        ),
        "differs" = paste0(
          "Contrast_", index, " does not estimate the declared hypothesis '",
          hypothesis_labels[index], "' (", declared_text, "): it estimates ",
          estimated_text, "."
        )
      )

      data.frame(
        Contrast = paste0("Contrast_", index),
        Hypothesis = hypothesis_labels[index],
        Declared = declared_text,
        Estimated = estimated_text,
        Status = status,
        Ratio = if (proportional) ratio else NA_real_,
        Message = message_text,
        stringsAsFactors = FALSE
      )
    }
  )

  table <- do.call(rbind, rows)

  list(
    table = table[, setdiff(names(table), "Message")],
    messages = table$Message
  )
}


#' Describe a set of levels suggested by a coding column
#'
#' @keywords internal
#' @noRd
.describe_level_set <- function(levels) {

  if (length(levels) == 0L) {
    return("(none)")
  }

  if (length(levels) == 1L) {
    return(levels)
  }

  paste0("Mean(", paste(levels, collapse = ", "), ")")
}


#' Check that displayed comparisons reconstruct the model coefficients
#'
#' Internal helper. Verifies `beta_j = scale_j * (sum(w_plus * eta) -
#' sum(w_minus * eta))` for each contrast, where `eta` are level-specific
#' predictions on the linear-predictor scale. The identity is exact for
#' additive models on the link scale, whatever values the other predictors
#' are fixed at, because each hypothesis row sums to zero.
#'
#' @param hypotheses Output of `.contrast_hypotheses()`.
#' @param coefficients Numeric vector of the focal contrast coefficients,
#'   in the order of the contrast columns.
#' @param level_values Numeric vector of link-scale level predictions, in
#'   the order of the factor levels.
#' @param tolerance Relative tolerance.
#'
#' @return A logical vector, one element per contrast.
#'
#' @keywords internal
#' @noRd
.check_hypothesis_identity <- function(hypotheses,
                                       coefficients,
                                       level_values,
                                       tolerance = 1e-6) {

  if (is.null(hypotheses$contrasts)) {

    implied <- as.numeric(hypotheses$hypothesis_matrix %*% level_values)

  } else {

    implied <- vapply(
      hypotheses$contrasts,
      function(contrast) {
        contrast$scale * sum((contrast$positive_weights - contrast$negative_weights) * level_values)
      },
      numeric(1)
    )
  }

  coefficients <- as.numeric(coefficients)

  abs(implied - coefficients) <= tolerance * pmax(1, abs(coefficients))
}

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.