contrasts_multpred: Decompose Interaction Contrasts into Interpretable...

View source: R/contrasts_multpred.R

contrasts_multpredR Documentation

Decompose Interaction Contrasts into Interpretable Configurations

Description

contrasts_multpred() decomposes model coefficients associated with interactions among categorical predictors into interpretable configurations of factor levels.

For each selected interaction coefficient, the function identifies the positive and negative level groups implied by the contrast matrices used to fit the model. It then returns observed means or model-based predictions for the resulting configurations.

One variable involved in each interaction is selected as the split variable. The contrasts of the remaining target variable or variables are then displayed within the levels or contrast-defined groups of the split variable.

The function supports two-way and higher-order interactions.

Usage

contrasts_multpred(
  model,
  data = NULL,
  interaction = NULL,
  coefficients = NULL,
  outcome = NULL,
  split_rule = c("last_variable", "first_variable", "lowest_complexity",
    "highest_complexity"),
  top_split = NULL,
  sig_level = 0.05,
  conf_level = 0.95,
  configuration = c("none", "all", "explicit", "semantic"),
  estimate_type = c("auto", "observed", "predicted"),
  prediction_scale = c("response", "link"),
  methodological_note = TRUE,
  bounds = NULL,
  hypotheses = NULL
)

Arguments

model

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

data

Optional data frame containing the variables used to fit model. If NULL, the data supplied in the model call are recovered, restricted to the rows used for fitting; the model frame is used only when they are unavailable. The original variables are needed for model-based estimates when the model contains transformed terms such as log(x). Rows of a supplied data frame that were excluded from the fit, through subset or missing values, are dropped, matching rows by name.

interaction

Optional character string identifying the interaction term to decompose, for example "A:B" or "A:B:C". When supplied, the interaction is resolved using the fitted model matrix and the coefficients associated with that interaction are selected automatically. If coefficients is also supplied, those coefficients are validated against the requested interaction. When both interaction and coefficients are NULL, all non-intercept coefficients containing ":" are analyzed, preserving the default behavior of this function.

coefficients

Optional character vector containing the interaction coefficients to decompose. If interaction is NULL and coefficients is NULL, all non-intercept coefficients containing ":" are analyzed. When interaction is supplied, coefficients may be used to select a subset of the coefficients belonging to that interaction.

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().

split_rule

Character string indicating how the split variable is selected for each interaction coefficient. Available options are:

"last_variable"

Selects the last variable appearing in the interaction coefficient.

"first_variable"

Selects the first variable appearing in the interaction coefficient.

"lowest_complexity"

Selects the variable with the lowest contrast-complexity score.

"highest_complexity"

Selects the variable with the highest contrast-complexity score.

top_split

Optional character string identifying a variable that must be used as the split variable. When supplied, top_split overrides split_rule.

sig_level

Numeric value indicating the significance threshold used to classify the original interaction coefficients as significant or non-significant. The default is 0.05.

conf_level

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

configuration

Character string controlling which configuration labels are included in the output. Available options are:

"none"

Does not return configuration-label columns.

"all"

Returns both explicit and semantic configuration labels.

"explicit"

Returns the complete mathematical composition of each configuration.

"semantic"

Returns a compact description of the levels or groups represented by each configuration.

estimate_type

Character string indicating which estimates are returned. Available options are:

"auto"

Uses observed means when every analyzed interaction involves all the predictors of the fixed part, the model has no random effects and no unequal prior weights, and, for generalized models, prediction_scale = "response". Model-based predictions are used otherwise, as in contrasts_onepred().

"observed"

Returns observed aggregated means computed directly from data.

"predicted"

Returns model-based predictions computed from the fixed-effect coefficients and their variance-covariance matrix.

prediction_scale

Character string indicating the scale on which model-based predictions are returned. Available options are:

"response"

Returns predictions on the response scale. For generalized models, the inverse link function is applied.

"link"

Returns predictions on the linear-predictor scale.

This argument is ignored when estimate_type = "observed".

methodological_note

Logical. Should a methodological note describing the settings relevant to the current analysis be printed? The default is TRUE. The note is stored as an attribute of the returned object regardless of this setting.

bounds

Optional numeric vector c(lower, upper) giving the natural range of a response analyzed with a Gaussian (identity link) model, such as c(1, 7) for a Likert score or c(0, Inf) for a reaction time. When supplied, confidence intervals of observed and predicted estimates are computed on a transformed scale (logit or logarithm) and transformed back, so that they remain within the bounds. Ignored, with a warning, for generalized models. See contrasts_onepred().

hypotheses

Optional named list declaring, for one or more categorical predictors, the comparisons that their contrast coefficients are intended to estimate, for example list(treatment = H_treatment, context = H_context). Each element is a numeric matrix with one row per contrast column of that predictor and one column per level, as the rows of a hypothesis matrix (see contrasts_onepred()). Each declared predictor is checked against the comparisons implied by its coding, and a message reports the result for each contrast column. Because the hypothesis of an interaction coefficient is the Kronecker product of the hypotheses of its components, each interaction coefficient estimates the product of the declared hypotheses when all its declared components do, multiplied by the product of their factors. Predictors not listed are not checked. The model is not modified. The result is stored in the hypothesis_check attribute, with one row per analyzed coefficient.

Details

Each interaction coefficient is separated into its contrast-coded components. The function then identifies:

  • the categorical predictor represented by each component;

  • the corresponding contrast column;

  • the factor levels receiving positive, negative, or zero weights.

One predictor is selected as the split variable. The remaining predictor or predictors are treated as target variables whose contrasts are interpreted within the levels or contrast-defined groups of the split variable.

For example, suppose that FactorA has three levels and uses Helmert contrasts, whereas FactorB has two levels and uses sliding-difference contrasts. If FactorB is selected as the split variable, the function displays the Helmert contrasts of FactorA separately within the levels or contrast-defined groups of FactorB.

Therefore, the split variable is not necessarily the variable of primary interpretive interest. It defines the conditions under which the contrasts of the remaining target variable or variables are displayed.

The split variable is selected separately for each interaction coefficient. Consequently, when all model interactions are analyzed simultaneously, more than one value may appear in the split_var column. For example, in a model containing A:B, A:C, B:C, and A:B:C, the variable selected by "highest_complexity" may differ across coefficients because only the variables involved in each coefficient are considered.

Random-effect grouping variables are excluded when identifying the categorical predictors involved in the fixed-effect interactions.

Value

A data frame of class "plot_ready_contrasts_df" with one row per decomposed configuration.

The returned columns include:

coefficient

Name of the original interaction coefficient being decomposed.

contrast_id

Sequential identifier assigned to the selected coefficient.

significance

Significance classification of the original coefficient: "Sig", "NotSig", or "NoPValue".

p_value

P-value associated with the original interaction coefficient, when available.

scale_factor

Scale factor such that the coefficient equals scale_factor multiplied by the displayed difference of differences on the linear-predictor scale.

split_var

Split variable selected for the coefficient.

factor columns

One column for each categorical predictor involved in the analyzed interactions. Values identify specific levels or aggregated groups.

n

Number of observed rows underlying the displayed configuration.

estimate

Observed aggregate or model-based aggregate.

se

Standard error of the displayed estimate.

ci_low

Lower confidence-interval boundary.

ci_high

Upper confidence-interval boundary.

Depending on configuration, the output may also include:

configuration_explicit

Mathematical description of the cells entering the aggregate.

configuration_semantic

Compact interpretation of the specific and averaged levels.

The returned object contains the following attributes:

note

Methodological description of the estimation and aggregation procedures.

estimate_type

Whether the output contains "observed" or "predicted" estimates.

prediction_scale

Prediction scale used for model-based estimates. This is NA for observed estimates.

estimate_info

Human-readable description of the estimate column.

pvalue_source

Source of the p-values, such as "model", "lmerTest", or "not_available".

split_rule

Rule used to select the split variable.

top_split

Split variable explicitly requested through top_split, when supplied.

scale_factors

Named vector of scale factors, one per coefficient.

identity_holds

Named logical vector indicating, for each coefficient, whether the displayed comparisons reconstruct the coefficient on the linear-predictor scale.

Contrast complexity and split selection

The options "lowest_complexity" and "highest_complexity" select the split variable according to the contrast coding assigned to each predictor.

Contrast systems are ranked using the following approximate scores:

  • Treatment contrasts: 0.

  • Sum contrasts: 1.

  • Sliding-difference contrasts: 1.

  • Helmert contrasts: 2.

  • Reverse Helmert contrasts: 2.

  • Polynomial contrasts: 3.

  • Custom or unidentified contrast matrices: 4.

These scores affect only the choice of split variable. They do not determine the order in which variables are displayed in the configuration labels.

If several variables have the same complexity score, the rightmost tied variable in the interaction coefficient is selected. A warning is issued to document the choice.

The argument top_split bypasses the automatic rule and forces the specified variable to be used as the split variable.

Ordering of configuration labels

Both explicit and semantic configuration labels use the following order:

target variable(s) -> split variable

The target variables are displayed first, following their stable order among the categorical predictors in the fixed-effects model. The split variable selected by split_rule or top_split is always displayed last.

For a two-way interaction between A and B, if A is the split variable, labels follow the order:

B_A

If B is the split variable, labels follow the order:

A_B

For a three-way interaction among A, B, and C, if C is the split variable, labels follow the order:

A_B_C

If A is the split variable, labels follow the order:

B_C_A

This ordering rule affects only the presentation and interpretation of the labels. It does not modify the contrast-complexity scores, the selected split variable, or the numerical estimates.

Explicit and semantic configurations

configuration_explicit reports the individual cells entering an aggregate. It is intended to show the exact mathematical composition of the displayed estimate.

For example:

(B2_A1 + B2_A2)/2

indicates that the estimate is the arithmetic mean of cells B2_A1 and B2_A2.

configuration_semantic reports the corresponding interpretation:

B2_Mean(A1,A2)

Both labels use the same variable order. In this example, B is the target variable and A is the split variable.

With B as the split variable, the corresponding labels could be:

(A1_B2 + A2_B2)/2
Mean(A1,A2)_B2

The explicit label answers the question, "Which cells were combined?", whereas the semantic label answers the question, "What does the resulting estimate represent?"

Raw estimates

For estimate_type = "observed", estimates are computed directly from the observed response values.

At the individual-cell level, the function returns the observed mean, standard error, and confidence interval.

When several disjoint cells are combined, their means are aggregated using normalized contrast weights. Standard errors are combined through classical variance propagation.

Confidence intervals for aggregated observed estimates use a Satterthwaite-like approximation to the degrees of freedom when sufficient information is available.

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 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 cell. 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.

Model-based predictions

For estimate_type = "predicted", predictions are computed from the fixed-effect model:

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

where X is the fixed-effect model matrix and \hat{\beta} is the vector of fixed-effect coefficients.

The covariance matrix of the linear predictors is obtained from:

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

where V_{\hat{\beta}} is the complete fixed-effect variance-covariance matrix.

In mixed-effects models, random effects are excluded. The returned predictions are therefore population-level or fixed-effect predictions.

Predictions are computed on a reference grid built for each coefficient. The grid crosses the levels of the factors involved in the coefficient with the levels of the other factors; numeric predictors are fixed at their observed means. Each displayed cell averages over the other factors with equal weights (a balanced average, independent of the observed cell sizes). A factor that interacts with the variables of the coefficient, such as C for a coefficient of A:B in a model containing A:B:C, is instead held at the combination of its levels at which the coefficient is defined, given by the first row of its hypothesis matrix: the balanced average for sum, Helmert, and sliding-difference coding, and the reference level for treatment coding.

Averaging the predictions of the observed rows of each cell would instead mix in the effects of covariates whose distribution differs between cells, so that the displayed interaction contrast would no longer correspond to the coefficient.

For glmmTMB models, only the conditional component is analyzed. Zero-inflation and dispersion components are not currently decomposed.

Response-scale predictions

For generalized models with prediction_scale = "response", each linear-predictor value is first transformed through the inverse link function. The transformed predictions are then averaged.

Therefore, the function computes:

\frac{1}{n} \sum_{i=1}^{n} g^{-1}(\hat{\eta}_i)

rather than:

g^{-1}\left( \frac{1}{n} \sum_{i=1}^{n} \hat{\eta}_i \right)

These two quantities are generally different when the inverse link is nonlinear.

Aggregation of predicted estimates

Model-based predictions for different configurations are generally correlated because they depend on the same fixed-effect coefficient vector.

contrasts_multpred() therefore does not combine predicted standard errors under an assumption of independence.

Instead, each configuration is represented by its weights over the rows of the reference grid, which are retained throughout the recursive decomposition. When configurations are aggregated, their weights are combined and the aggregate is calculated directly from the complete fixed-effect variance-covariance matrix.

On the link scale, an aggregated prediction with normalized weights a_i is:

\hat{\theta} = \sum_i a_i X_i\hat{\beta}

Defining:

L = \sum_i a_i X_i

its variance is:

\mathrm{Var}(\hat{\theta}) = L V_{\hat{\beta}} L^\mathsf{T}

On the response scale, the aggregated prediction is:

\hat{\theta} = \sum_i a_i g^{-1}(X_i\hat{\beta})

Its variance is approximated using the multivariate delta method. The gradient is:

\nabla\hat{\theta} = \sum_i a_i g^{-1\prime}(\hat{\eta}_i) X_i

and:

\mathrm{Var}(\hat{\theta}) \approx \nabla\hat{\theta} V_{\hat{\beta}} \nabla\hat{\theta}^{\mathsf{T}}

This procedure preserves the covariance among the predictions entering each aggregate.

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.

Supported contrast types

The function supports treatment contrasts (with any reference level), sum contrasts (with any omitted level), Helmert, reverse Helmert, and sliding-difference contrasts, and custom contrast matrices.

For every factor, the levels compared by each contrast column and their weights are taken from the hypothesis matrix H = [1, C]^{-1} of its coding matrix C, as described in contrasts_onepred(). Reading them from the signs of C is correct only for orthogonal codings. Groups of levels with unequal weights, which arise with non-orthogonal custom codings, are labelled ⁠W(a1 .20, a3 .80)⁠, and a message describes the comparison actually estimated when it differs from the one suggested by the signs of the coding column.

Sum contrasts are interpreted as a focal level relative to the unweighted mean across all levels of the corresponding factor.

Scale factors

The hypothesis of an interaction coefficient is the Kronecker product of the hypothesis rows of its components. Each interaction coefficient therefore equals the product of the scale factors of its components, returned in scale_factor, multiplied by the displayed difference of differences on the linear-predictor scale. For example, the interaction between the second column of a Helmert-coded factor (s = 1/3) and a sum-coded factor (s = 1) has s = 1/3.

The function verifies this identity for each coefficient. For predicted estimates it holds exactly unless a variable of the coefficient interacts with a numeric predictor, in which case a warning is issued. For observed estimates it holds only when the model contains the interacting factors alone.

Polynomial contrasts are not currently supported for interaction decomposition because all levels generally contribute to each polynomial component through nonzero weights and require a different interpretive strategy.

P-values

P-values refer to the original interaction coefficients being decomposed. They are not direct tests of the individual configuration-specific estimates displayed in the output.

The function recognizes coefficient-table columns named:

  • "Pr(>|t|)";

  • "Pr(>|z|)";

  • "p-value".

Models fitted with lme4::lmer() do not ordinarily provide p-values. When lmerTest is installed, the model is converted internally using lmerTest::as_lmerModLmerTest(), and approximate p-values are extracted from the resulting coefficient table.

If no p-values are available, p_value is set to NA and significance is set to "NoPValue".

Examples

###############################################################
## Two-way interaction
###############################################################


library(lme4)
library(MASS)

set.seed(123)

dat <- expand.grid(
  ID = factor(paste0("S", 1:40)),
  A = factor(c("A1", "A2", "A3")),
  B = factor(c("B1", "B2", "B3", "B4")),
  Rep = 1:2
)

contrasts(dat$A) <- stats::contr.helmert(3)
contrasts(dat$B) <- MASS::contr.sdif(4)

random_intercept <- rnorm(
  nlevels(dat$ID),
  mean = 0,
  sd = 1
)

effect_A <- c(
  A1 = 0,
  A2 = 1,
  A3 = 2
)

effect_B <- c(
  B1 = 0,
  B2 = 0.5,
  B3 = 1.5,
  B4 = 2.5
)

dat$Score <- 10 +
  effect_A[dat$A] +
  effect_B[dat$B] +
  0.7 * effect_A[dat$A] * effect_B[dat$B] +
  random_intercept[dat$ID] +
  rnorm(nrow(dat), mean = 0, sd = 1.5)

mod <- lme4::lmer(
  Score ~ A * B + (1 | ID),
  data = dat
)

# A is selected as the conditioning variable.
# Labels follow the order B -> A.
out_high <- contrasts_multpred(
  model = mod,
  outcome = "Score",
  estimate_type = "predicted",
  split_rule = "highest_complexity",
  configuration = "all"
)

# B is selected as the conditioning variable.
# Labels follow the order A -> B.
out_low <- contrasts_multpred(
  model = mod,
  outcome = "Score",
  estimate_type = "predicted",
  split_rule = "lowest_complexity",
  configuration = "all"
)


###############################################################
## Three-way interaction
###############################################################

dat3 <- expand.grid(
  ID = factor(paste0("S", 1:30)),
  A = factor(c("A1", "A2", "A3")),
  B = factor(c("B1", "B2", "B3", "B4")),
  C = factor(c("C1", "C2")),
  Rep = 1:2
)

contrasts(dat3$A) <- stats::contr.helmert(3)
contrasts(dat3$B) <- MASS::contr.sdif(4)
contrasts(dat3$C) <- stats::contr.treatment(2)

dat3$Score <- 10 +
  effect_A[dat3$A] +
  effect_B[dat3$B] +
  1.2 * (dat3$C == "C2") +
  0.4 * effect_A[dat3$A] * effect_B[dat3$B] +
  rnorm(nrow(dat3), mean = 0, sd = 1.5)

mod3 <- stats::lm(
  Score ~ A * B * C,
  data = dat3
)

out3 <- contrasts_multpred(
  model = mod3,
  outcome = "Score",
  estimate_type = "predicted",
  split_rule = "highest_complexity",
  configuration = "all"
)


###############################################################
## glmmTMB model
###############################################################

eta_count <- 1.2 +
  0.2 * effect_A[dat$A] +
  0.15 * effect_B[dat$B]

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

mod_tmb <- glmmTMB::glmmTMB(
  count ~ A * B + (1 | ID),
  family = poisson,
  data = dat
)

out_tmb <- contrasts_multpred(
  model = mod_tmb,
  outcome = "count",
  estimate_type = "predicted",
  prediction_scale = "response",
  split_rule = "highest_complexity",
  configuration = "semantic"
)



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