contrasts_onepred: Summarize and Interpret Contrasts for One Categorical...

View source: R/contrasts_onepred.R

contrasts_onepredR Documentation

Summarize and Interpret Contrasts for One Categorical Predictor

Description

contrasts_onepred() returns observed or model-based estimates associated with the contrasts used to code a single categorical predictor in a fitted regression model.

The function identifies the predictor's contrast coding and returns the estimates for the levels or groups of levels involved in each contrast.

The function supports standard linear and generalized linear models, mixed-effects models fitted with lme4, mixed-effects models fitted with nlme, and conditional models fitted with glmmTMB.

Usage

contrasts_onepred(
  model,
  predictor,
  data = NULL,
  outcome = NULL,
  sig_level = 0.05,
  conf_level = 0.95,
  estimate_type = c("auto", "observed", "predicted"),
  prediction_scale = c("response", "link"),
  bounds = NULL,
  hypotheses = NULL
)

Arguments

model

A fitted model object. Supported classes include objects returned by stats::lm(), stats::glm(), lme4::lmer(), lme4::glmer(), nlme::lme(), and glmmTMB::glmmTMB().

predictor

Character string indicating the name of the categorical predictor whose contrasts should be summarized. The corresponding variable in data must be a factor.

data

Optional data frame containing the variables used to fit model. If NULL, the data supplied in the model call are recovered. Rows excluded from the fit, through subset or missing values, are dropped, matching rows by name. Factors are given the contrasts used for fitting, including those supplied through the contrasts argument of the model call.

outcome

Optional character string indicating the name of the dependent variable; by default, the dependent variable of model. It is used only for observed estimates, which summarize the response of the model evaluated in data: a transformed response such as log(y) is summarized on the scale of the model, and a logical response or a factor response of a binomial model is converted to 0/1 as in stats::glm() (the first level is 0). Observed estimates are not available for responses with several columns, such as cbind(successes, failures).

sig_level

Numeric value indicating the significance threshold used to classify contrasts as "sig" or "notsig". The default is 0.05.

conf_level

Numeric value indicating the confidence level used for confidence intervals. The default is 0.95.

estimate_type

Character string specifying how the level-specific estimates should be computed. Available options are:

"auto"

Uses observed means when the fixed part of the model contains only the focal predictor, the model has no random effects and no unequal prior weights, and, for generalized models, prediction_scale = "response". Model-based predictions are used otherwise: with other predictors or interactions, with random effects (observed means would ignore the clustering of the observations), with weights (observed means are unweighted), and for estimates on the link scale.

"observed"

Computes observed means directly from the supplied data.

"predicted"

Computes model-based predictions from the fixed effects and their variance-covariance matrix.

The default is "auto".

prediction_scale

Character string indicating the scale used for model-based predictions. Available options are:

"response"

Predictions are reported on the response scale. For generalized models, the inverse link function is applied.

"link"

Predictions are reported on the linear-predictor scale.

This argument is relevant only when estimate_type = "predicted".

bounds

Optional numeric vector c(lower, upper) giving the natural range of the response, for responses analyzed with a Gaussian (identity link) model, such as a Likert score (c(1, 7)), a percentage (c(0, 100)), or a reaction time (c(0, Inf)). The bounds cannot be inferred from the data, because the observed range need not coincide with the possible range. When supplied, confidence intervals of observed and predicted estimates are computed on a transformed scale and transformed back, so that they remain within the bounds: the logit of (m - a)/(b - a) for two finite bounds, and the logarithm of the distance from the finite bound otherwise. Estimates are unchanged. The argument is ignored, with a warning, for generalized models, whose intervals already respect the range implied by their family. Bounds correct the representation of uncertainty, not the model: when many observations lie at a bound, a model suited to the scale of the response (for example an ordinal model) is more appropriate.

hypotheses

Optional numeric matrix declaring the comparisons that the coefficients of predictor are intended to estimate, with one row per coefficient, in the order of the contrast columns, and one column per factor level, as the rows of a hypothesis matrix (for example rbind("Treat-Control" = c(-1, 0.5, 0.5), "T2-Control" = c(-1, 0, 1))). Each row must sum to zero. Column names, when present, must be the factor levels; row names label the hypotheses. Each declared row is compared with the comparison that the coefficient actually estimates, and a message reports whether the coefficient estimates the declared hypothesis, exactly, up to a positive factor, or with reversed sign, or which comparison it estimates instead. The model is not modified: the function reports what the fitted coding estimates. The result is stored in the hypothesis_check attribute.

Details

The function retrieves the contrast (coding) matrix used for predictor and derives from it the hypothesis matrix, which states the combination of level-specific means estimated by each coefficient. The levels contributing positively and negatively to each contrast, and their weights, are taken from the hypothesis matrix (see the section "Coding matrix and hypothesis matrix").

Model-based predictions are computed manually from the fixed-effects model:

\hat{\eta} = X\hat{\beta}

Their variance on the linear-predictor scale is computed as:

\mathrm{Var}(\hat{\eta}) = X V_{\hat{\beta}} X^\mathsf{T}

where X is the fixed-effects model matrix and V_{\hat{\beta}} is the variance-covariance matrix of the fixed-effect coefficients.

For estimate_type = "observed", estimates are observed means computed directly from the data.

Confidence intervals of observed means respect the natural range of the response. For proportions (binary outcomes or binomial models), the Wilson score interval is used; for averages of several levels or cells it is computed with the effective sample size \hat{p}(1 - \hat{p}) / \mathrm{SE}^2, which reduces to the classical Wilson interval for a single level. For positive responses analyzed with count or positive-continuous families (for example Poisson, negative binomial, or Gamma), the interval is computed on the log scale, \exp(\log m \pm z\,\mathrm{SE}/m); a mean of zero receives the exact Poisson upper bound -\log(\alpha/2)/n. Other responses use symmetric intervals.

For estimate_type = "predicted", estimates are computed from the fixed-effect coefficients and their variance-covariance matrix.

In mixed-effects models, random effects are excluded from model-based predictions. Predicted estimates are therefore population-level or fixed-effects predictions.

Model-based estimates are computed on a reference grid. Other numeric predictors are fixed at their observed means. Each level-specific estimate averages over the levels of the other categorical predictors with equal weights (a balanced average, independent of the observed cell sizes). A categorical predictor that interacts with predictor is instead held at the combination of its levels at which the coefficients of predictor are defined, given by the first row of its hypothesis matrix: this is again the balanced average for sum, Helmert, and sliding-difference coding, and the reference level for treatment coding. On the linear-predictor scale, the displayed comparisons therefore reconstruct the coefficients exactly; if predictor interacts with a numeric predictor, its coefficients refer to the value zero of that predictor and the function issues a warning.

On the response scale, level estimates that average over other factors are means of the response-scale predictions, and their confidence intervals are obtained with the multivariate delta method.

For generalized models with prediction_scale = "response", estimates are transformed using the inverse link function. Standard errors on the response scale are approximated using the delta method.

On the response scale, the confidence interval of a prediction or of an average of predictions \hat{\theta} is computed on the link scale and transformed back,

g^{-1}\left(g(\hat{\theta}) \pm z \, \frac{\mathrm{SE}(\hat{\theta})}{\left|g^{-1\prime}(g(\hat{\theta}))\right|}\right),

so that its bounds remain within the range of the response (for example between 0 and 1 for probabilities). For a single prediction this is the interval computed on the linear predictor and transformed with the inverse link. The interval is therefore generally asymmetric around the estimate, whereas the reported standard error refers to the response scale.

For non-polynomial contrasts involving more than one level on the positive or negative side, the reported group estimate is the weighted mean of the corresponding level-specific estimates, with weights taken from the hypothesis matrix. For all standard codings these weights are equal, so the group estimate is the unweighted arithmetic mean. Groups with unequal weights, which arise with non-orthogonal custom codings, are labelled ⁠W(A .20, C .80)⁠.

Standard errors of groups of observed means treat the level means as independent. Standard errors of groups of model-based predictions use the complete variance-covariance matrix of the fixed effects; on the response scale they are obtained with the multivariate delta method, and the confidence intervals are computed on the link scale as described above.

The Significance label refers to the p-value of the model coefficient associated with the corresponding contrast. It does not represent a direct test of the individual level-specific estimates or their confidence intervals.

For glmmTMB objects, only the conditional model component, cond, is analyzed. Zero-inflation and dispersion components are not currently summarized.

Value

A data frame with one or more rows per contrast.

For non-polynomial contrasts, the output contains two rows per contrast, the positive and the negative side, and includes:

Contrast

Name or sequential identifier of the contrast.

Levels

Factor level or group of levels represented by the contrast: a level name, "Mean(A, B)" for equally weighted groups, "W(A .20, C .80)" for groups with unequal weights, or "Grand Mean" for sum contrasts.

Estimate

Observed mean or model-based estimate.

SE

Standard error of the reported estimate.

CI_low

Lower confidence-interval boundary.

CI_high

Upper confidence-interval boundary.

Significance

Significance label associated with the corresponding model coefficient: "sig", "notsig", or NA.

Scale_factor

Scale factor s_j such that the model coefficient equals s_j multiplied by the difference between the two displayed quantities on the linear-predictor scale. It equals 1 for treatment, sum, and sliding-difference contrasts.

Display_Levels

Labels used for display; currently identical to Levels.

For polynomial contrasts, the output contains one row per factor level for each polynomial component, has no Scale_factor column, and additionally includes:

Weight

Polynomial contrast weight associated with each factor level.

Polynomial_fit

Curve implied by the single polynomial component: the mean of the level estimates on the linear-predictor scale plus the component coefficient multiplied by the polynomial weight, transformed to the scale of Estimate (for example with the inverse logit for a binomial model on the response scale). The baseline is computed on the same reference grid as the estimates, so that the curve passes through the region of the displayed points. On the linear-predictor scale, the baseline plus the sum of all components reproduces every level estimate.

The returned object also contains the following attributes:

disclaimer

Description of how estimates, standard errors, and confidence intervals were computed, including any note on non-orthogonal custom codings. The same information is printed as a message when the function is executed.

contrast_type

The identified contrast type.

hypothesis_matrix

The hypothesis matrix H without the intercept row, with one row per contrast and one column per factor level.

family, link, estimate_type, prediction_scale

Model family and link (NA when unavailable) and the settings used.

Sum contrasts and the Grand Mean

For sum-to-zero contrasts, each contrast is displayed as a comparison between one factor level and a row labelled "Grand Mean".

The Grand Mean is defined as the unweighted arithmetic mean of the level-specific estimates. Each factor level therefore contributes equally, regardless of its sample size.

When estimate_type = "observed", the Grand Mean is:

\frac{\bar{Y}_1 + \bar{Y}_2 + \cdots + \bar{Y}_k}{k}

where \bar{Y}_j is the observed mean for level j.

When estimate_type = "predicted" and prediction_scale = "link", the Grand Mean is the arithmetic mean of the level-specific linear predictors:

\frac{\hat{\eta}_1 + \hat{\eta}_2 + \cdots + \hat{\eta}_k}{k}

With sum contrasts, this quantity generally corresponds to the model intercept when the remaining predictors are fixed at the values used to construct the prediction data.

When estimate_type = "predicted" and prediction_scale = "response", the Grand Mean is the arithmetic mean of the response-scale predictions:

\frac{ g^{-1}(\hat{\eta}_1) + g^{-1}(\hat{\eta}_2) + \cdots + g^{-1}(\hat{\eta}_k) }{k}

This is not generally equal to applying the inverse link function to the average linear predictor:

g^{-1}\left(\frac{1}{k}\sum_j \hat{\eta}_j\right) \neq \frac{1}{k}\sum_j g^{-1}(\hat{\eta}_j)

For a binomial model with a logit link, the response-scale Grand Mean is the arithmetic mean of the predicted probabilities.

For a Poisson or negative-binomial model with a log link, the response-scale Grand Mean is the arithmetic mean of the predicted expected counts.

The standard error of an observed Grand Mean is computed by treating the level-specific observed means as independent estimates.

The standard error of a predicted Grand Mean is computed using the complete variance-covariance matrix of the fixed-effect coefficients. On the response scale, the required gradient is obtained using the multivariate delta method.

Coding matrix and hypothesis matrix

The contrast matrix C describes how the factor is coded in the model. It does not, in general, describe what the coefficients compare. For a factor with k levels and k - 1 contrasts, the level-specific means satisfy

\mu = X_C \beta, \qquad X_C = [1, C],

so that

\beta = H \mu, \qquad H = X_C^{-1}.

Row h_j of H states the combination of level means estimated by coefficient \beta_j. The function always derives the compared levels from H. Reading them from the signs of C is correct only for orthogonal codings; for non-orthogonal custom codings it can display a comparison different from the one estimated by the coefficient. If X_C is not full rank, the function stops.

Every non-intercept row of H sums to zero and is written as

h_j = s_j (w^+_j - w^-_j),

where w^+_j and w^-_j are non-negative weights summing to one (the two displayed groups) and s_j > 0 is the scale factor returned in Scale_factor. Consequently,

\beta_j = s_j \left(\sum_i w^+_{ji} \mu_i - \sum_i w^-_{ji} \mu_i\right).

On the linear-predictor scale this identity holds exactly for model-based predictions of an additive model, whatever values the other predictors are fixed at, because each row of H sums to zero. The function verifies it and issues a warning when it fails, which usually indicates that the predictor is involved in an interaction. For observed means, the identity holds only when the model contains the focal predictor alone; the disclaimer reports when it does not.

For non-orthogonal custom codings, the function also compares the levels suggested by the signs of each coding column with the levels involved in the corresponding hypothesis. When they differ, a message describes the comparison actually estimated by the coefficient.

Contrast types

The contrast type is identified from the coding matrix and, for matrices that do not coincide with a standard generator, from the structure of the hypothesis matrix. It determines only the presentation of the comparisons; their content always comes from the hypothesis matrix. The function recognizes:

  • Treatment contrasts, with any reference level (for example stats::contr.treatment() with any base, or stats::contr.SAS()): each level versus the reference level, s = 1.

  • Sum contrasts, with any omitted level (for example stats::contr.sum()): each level versus the Grand Mean, s = 1.

  • Helmert contrasts generated by stats::contr.helmert(): each level versus the mean of the preceding levels, s_j = 1 / (j + 1).

  • Reverse Helmert contrasts generated by reverse_helmert(): each level versus the mean of the subsequent levels, s_j = 1 / (k - j + 1).

  • Sliding-difference contrasts generated by MASS::contr.sdif(): each level versus the preceding level, s = 1.

  • Polynomial contrasts generated by stats::contr.poly(), with equally spaced or user-supplied scores.

  • Other user-defined (custom) contrast matrices, displayed as the two weighted groups of levels implied by the hypothesis matrix, with an arbitrary scale factor.

Rescaled versions of these codings are recognized as well; rescaling a coding column changes only the scale factor.

Sum contrasts are displayed as one level versus the Grand Mean of all levels, which includes the focal level. This presentation is equivalent to the split of the hypothesis row into disjoint groups and is used because it matches the usual interpretation of sum coding.

Polynomial contrasts are handled separately because all factor levels contribute to each polynomial component through their polynomial weights, so that a split into positive and negative groups is not meaningful. For each component, the function returns one row per factor level and reports both the polynomial weight and the fitted curve implied by that component.

P-values

P-values are extracted from the coefficient table associated with the fixed-effects or conditional component of the model.

The function recognizes coefficient-table columns named:

  • "Pr(>|t|)";

  • "Pr(>|z|)";

  • "p-value".

Only the main-effect coefficients associated with predictor are used. Interaction coefficients involving predictor are excluded.

For model classes that do not provide frequentist p-values, the Significance column is set to NA.

Examples

###############################################################
## Linear model with treatment contrasts
###############################################################

set.seed(123)

dat <- data.frame(
  group = factor(rep(c("A", "B", "C"), each = 40))
)

dat$y <- c(
  rnorm(40, mean = 10, sd = 2),
  rnorm(40, mean = 13, sd = 2),
  rnorm(40, mean = 17, sd = 2)
)

contrasts(dat$group) <- contr.treatment(3)

mod_lm <- lm(
  y ~ group,
  data = dat
)

contrasts_onepred(
  model = mod_lm,
  predictor = "group",
  outcome = "y",
  data = dat,
  estimate_type = "observed"
)

contrasts_onepred(
  model = mod_lm,
  predictor = "group",
  outcome = "y",
  data = dat,
  estimate_type = "predicted"
)


###############################################################
## Generalized linear model with sum contrasts
###############################################################

contrasts(dat$group) <- contr.sum(3)

dat$binary_y <- rbinom(
  nrow(dat),
  size = 1,
  prob = plogis(
    -1 +
      0.5 * (dat$group == "B") +
      1.2 * (dat$group == "C")
  )
)

mod_glm <- glm(
  binary_y ~ group,
  family = binomial,
  data = dat
)

contrasts_onepred(
  model = mod_glm,
  predictor = "group",
  outcome = "binary_y",
  data = dat,
  estimate_type = "predicted",
  prediction_scale = "response"
)


###############################################################
## Linear model with polynomial contrasts
###############################################################

dat$ordered_group <- ordered(
  dat$group,
  levels = c("A", "B", "C")
)

contrasts(dat$ordered_group) <- contr.poly(3)

mod_poly <- lm(
  y ~ ordered_group,
  data = dat
)

contrasts_onepred(
  model = mod_poly,
  predictor = "ordered_group",
  outcome = "y",
  data = dat,
  estimate_type = "predicted"
)


###############################################################
## Mixed-effects models
###############################################################


library(lme4)
library(nlme)
library(glmmTMB)
library(MASS)

set.seed(123)

dat_mixed <- expand.grid(
  id = factor(1:60),
  time = 1:5
)

dat_mixed$group <- factor(
  sample(
    c("A", "B", "C"),
    nrow(dat_mixed),
    replace = TRUE
  )
)

random_intercept <- rnorm(
  nlevels(dat_mixed$id),
  mean = 0,
  sd = 1
)

eta <- 10 +
  0.3 * dat_mixed$time +
  2 * (dat_mixed$group == "B") +
  5 * (dat_mixed$group == "C") +
  random_intercept[dat_mixed$id]

dat_mixed$y <- eta +
  rnorm(
    nrow(dat_mixed),
    mean = 0,
    sd = 2
  )


## Linear mixed model with Helmert contrasts

contrasts(dat_mixed$group) <- contr.helmert(3)

mod_lmer <- lmer(
  y ~ group + time + (1 | id),
  data = dat_mixed
)

contrasts_onepred(
  model = mod_lmer,
  predictor = "group",
  outcome = "y",
  data = dat_mixed,
  estimate_type = "predicted"
)


## Linear mixed model fitted with nlme and sliding differences

contrasts(dat_mixed$group) <- MASS::contr.sdif(3)

mod_lme <- nlme::lme(
  y ~ group + time,
  random = ~1 | id,
  data = dat_mixed
)

contrasts_onepred(
  model = mod_lme,
  predictor = "group",
  outcome = "y",
  data = dat_mixed,
  estimate_type = "predicted"
)


## Generalized mixed model with sum contrasts

contrasts(dat_mixed$group) <- contr.sum(3)

eta_count <- 1.5 +
  0.2 * dat_mixed$time +
  0.3 * (dat_mixed$group == "B") +
  0.7 * (dat_mixed$group == "C") +
  random_intercept[dat_mixed$id]

dat_mixed$count <- rpois(
  nrow(dat_mixed),
  lambda = exp(eta_count)
)

mod_tmb <- glmmTMB(
  count ~ group + time + (1 | id),
  family = poisson,
  data = dat_mixed
)

contrasts_onepred(
  model = mod_tmb,
  predictor = "group",
  outcome = "count",
  data = dat_mixed,
  estimate_type = "predicted",
  prediction_scale = "response"
)



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