View source: R/contrasts_multpred.R
| contrasts_multpred | R Documentation |
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.
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
)
model |
A fitted model object. Supported model classes include objects
returned by |
data |
Optional data frame containing the variables used to fit
|
interaction |
Optional character string identifying the interaction
term to decompose, for example |
coefficients |
Optional character vector containing the interaction
coefficients to decompose. If |
outcome |
Optional character string indicating the name of the
dependent variable; by default, the dependent variable of |
split_rule |
Character string indicating how the split variable is selected for each interaction coefficient. Available options are:
|
top_split |
Optional character string identifying a variable that must
be used as the split variable. When supplied, |
sig_level |
Numeric value indicating the significance threshold used
to classify the original interaction coefficients as significant or
non-significant. The default is |
conf_level |
Numeric value indicating the confidence level used for
confidence intervals. The default is |
configuration |
Character string controlling which configuration labels are included in the output. Available options are:
|
estimate_type |
Character string indicating which estimates are returned. Available options are:
|
prediction_scale |
Character string indicating the scale on which model-based predictions are returned. Available options are:
This argument is ignored when |
methodological_note |
Logical. Should a methodological note describing
the settings relevant to the current analysis be printed? The default is
|
bounds |
Optional numeric vector |
hypotheses |
Optional named list declaring, for one or more
categorical predictors, the comparisons that their contrast coefficients
are intended to estimate, for example
|
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.
A data frame of class "plot_ready_contrasts_df" with one row per
decomposed configuration.
The returned columns include:
coefficientName of the original interaction coefficient being decomposed.
contrast_idSequential identifier assigned to the selected coefficient.
significanceSignificance classification of the original coefficient:
"Sig", "NotSig", or "NoPValue".
p_valueP-value associated with the original interaction coefficient, when available.
scale_factorScale factor such that the coefficient equals scale_factor
multiplied by the displayed difference of differences on the
linear-predictor scale.
split_varSplit variable selected for the coefficient.
One column for each categorical predictor involved in the analyzed interactions. Values identify specific levels or aggregated groups.
nNumber of observed rows underlying the displayed configuration.
estimateObserved aggregate or model-based aggregate.
seStandard error of the displayed estimate.
ci_lowLower confidence-interval boundary.
ci_highUpper confidence-interval boundary.
Depending on configuration, the output may also include:
configuration_explicitMathematical description of the cells entering the aggregate.
configuration_semanticCompact interpretation of the specific and averaged levels.
The returned object contains the following attributes:
noteMethodological description of the estimation and aggregation procedures.
estimate_typeWhether the output contains "observed" or "predicted" estimates.
prediction_scalePrediction scale used for model-based estimates. This is NA for observed
estimates.
estimate_infoHuman-readable description of the estimate column.
pvalue_sourceSource of the p-values, such as "model", "lmerTest", or
"not_available".
split_ruleRule used to select the split variable.
top_splitSplit variable explicitly requested through top_split, when
supplied.
scale_factorsNamed vector of scale factors, one per coefficient.
identity_holdsNamed logical vector indicating, for each coefficient, whether the displayed comparisons reconstruct the coefficient on the linear-predictor scale.
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.
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.
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?"
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.
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.
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.
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.
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.
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 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".
###############################################################
## 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"
)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.