The matrix that R stores for a factor, set with
contrasts(), is the coding matrix \(C\): its columns code the factor in the
model matrix. What the coefficients estimate is described by a different
matrix, the hypothesis matrix \(H\), whose rows state the combination of
level means estimated by each coefficient. For a factor with \(k\) levels and \(k - 1\) contrasts, the level means satisfy
\(\mu = [\mathbf{1}, C]\,\beta\), so
that
\[ \beta = H\mu, \qquad H = [\mathbf{1}, C]^{-1}. \]
MoPlot always derives the compared levels from \(H\), never from the signs of \(C\). For standard codings, the two readings agree up to sign and scale. For orthogonal custom codings they agree too. For non-orthogonal custom codings, however, they can differ, and a coding written from the intended hypotheses can estimate different comparisons.
Each row of \(H\) can be written as
\(h_j = s_j (w_j^{+} - w_j^{-})\), two
groups of levels with weights summing to one and a scale factor \(s_j\): the coefficient equals \(s_j\) times the difference between the two
groups. A group with unequal weights is labelled
W(A .20, C .80).
A study compares a control condition with two treatments. The
researchers want to know whether the treatments, taken together, improve
on the control condition, and whether T2 improves on it. A
natural, but wrong, way to encode these questions is to write their
weights directly as the coding columns:
set.seed(2)
trial <- data.frame(group = factor(rep(c("Control", "T1", "T2"), each = 30),
levels = c("Control", "T1", "T2")))
trial$score <- rnorm(90, mean = c(10, 12, 15)[trial$group], sd = 3)
intended <- rbind("Treat-Control" = c(Control = -1, T1 = 0.5, T2 = 0.5),
"T2-Control" = c(Control = -1, T1 = 0, T2 = 1))
trial_written <- trial
contrasts(trial_written$group) <- t(intended)
fit_written <- lm(score ~ group, data = trial_written)
round(coef(fit_written)[-1], 2)
#> groupTreat-Control groupT2-Control
#> -0.77 2.37The coefficients suggest that the treatments do not improve on the control condition, but they do not estimate the intended comparisons. Without further information, MoPlot can only note that the signs of the coding columns do not describe the comparisons estimated:
written <- contrasts_onepred(fit_written, "group")
#> Contrast_1: the signs of the coding column suggest Mean(T1, T2) vs Control, whereas the coefficient estimates 4/3 x [T1 - Mean(Control, T2)]. This is expected when the coding was derived from a hypothesis matrix (for example with MASS::ginv() or hypr). To check the intended comparisons, supply them through `hypotheses`.
#> Contrast_2: the signs of the coding column suggest T2 vs Control, whereas the coefficient estimates T2 - T1. This is expected when the coding was derived from a hypothesis matrix (for example with MASS::ginv() or hypr). To check the intended comparisons, supply them through `hypotheses`.The note does not say that the coding is wrong: a coding correctly derived from a hypothesis matrix also has columns that do not resemble the comparisons, as shown below. MoPlot cannot know what you intended.
The argument hypotheses declares the intended
comparisons, as the rows of a hypothesis matrix: one row per
coefficient, in the order of the contrast columns, and one column per
level, with weights summing to zero. Row names label the hypotheses;
column names, when present, must be the levels and may be in any
order.
written <- contrasts_onepred(fit_written, "group", hypotheses = intended)
#> Contrast_1 does not estimate the declared hypothesis 'Treat-Control' (Mean(T1, T2) - Control): it estimates 4/3 x [T1 - Mean(Control, T2)].
#> Contrast_2 does not estimate the declared hypothesis 'T2-Control' (T2 - Control): it estimates T2 - T1.
attr(written, "hypothesis_check")
#> Contrast Hypothesis Declared
#> 1 Contrast_1 Treat-Control Mean(T1, T2) - Control
#> 2 Contrast_2 T2-Control T2 - Control
#> Estimated Status Ratio
#> 1 4/3 x [T1 - Mean(Control, T2)] differs NA
#> 2 T2 - T1 differs NANeither coefficient estimates its declared hypothesis. The first
compares T1 with the mean of the control condition and
T2, multiplied by 4/3; the second compares T2
with T1. MoPlot does not correct the model, refit it, or
change its coding: it reports what the fitted coding estimates. The
figure shows these estimated comparisons, and its caption reports the
result of the check:
moplot_onepred(fit_written, "group", hypotheses = intended, style = "publication")
#>
#> Plot caption:
#>
#> This plot summarizes the contrasts for the categorical predictor group in the fitted model for score.
#> Under custom coding, each contrast represents a user-defined comparison rather than a standard contrast pattern.
#> C1 and C2 do not estimate the declared hypotheses; the figure shows the comparisons that the coefficients estimate.
#> Points in the upper panel represent the observed means for the quantities involved in each comparison, and error bars represent their confidence intervals.
#> Dashed segments connect the quantities specified by each user-defined contrast.
#> Abbreviated factor labels are used where needed for readability: Cont. = Control.
#> Labels C1 and C2 and so forth identify the corresponding contrasts; an asterisk indicates p < 0.050.
#> The lower panel displays the model coefficient for each contrast, together with its confidence interval and an approximate Cohen's d.
#> Each coefficient (indicated as Coef. 1, Coef. 2, and so forth) is horizontally aligned with the center of the corresponding comparison in the upper panel.
#> Under this coding, each model coefficient equals a scale factor s multiplied by the difference displayed in the upper panel on the linear-predictor scale (s = 4/3 for C1, s = 1 for C2).The comparisons estimated by the coding written from the hypotheses.
The coding that estimates the intended comparisons is obtained from the hypothesis matrix with the generalized inverse:
coding <- MASS::ginv(intended)
dimnames(coding) <- list(levels(trial$group), rownames(intended))
round(coding, 2)
#> Treat-Control T2-Control
#> Control -0.67 0
#> T1 1.33 -1
#> T2 -0.67 1
trial_derived <- trial
contrasts(trial_derived$group) <- coding
fit_derived <- lm(score ~ group, data = trial_derived)
derived <- contrasts_onepred(fit_derived, "group", hypotheses = intended)
#> Contrast_1 estimates the declared hypothesis 'Treat-Control': Mean(T1, T2) - Control.
#> Contrast_2 estimates the declared hypothesis 'T2-Control': T2 - Control.
round(coef(fit_derived)[-1], 2)
#> groupTreat-Control groupT2-Control
#> 2.39 3.58The check now confirms both hypotheses, and the coefficients equal the intended differences. Note that the correct coding column for Treat-Control, approximately \((-0.67, 1.33, -0.67)\), bears no resemblance to the comparison it estimates.
moplot_onepred(fit_derived, "group", hypotheses = intended, style = "publication")
#>
#> Plot caption:
#>
#> This plot summarizes the contrasts for the categorical predictor group in the fitted model for score.
#> Under custom coding, each contrast represents a user-defined comparison rather than a standard contrast pattern.
#> Each coefficient estimates the corresponding declared hypothesis.
#> Points in the upper panel represent the observed means for the quantities involved in each comparison, and error bars represent their confidence intervals.
#> Dashed segments connect the quantities specified by each user-defined contrast.
#> Abbreviated factor labels are used where needed for readability: Cont. = Control.
#> Labels C1 and C2 and so forth identify the corresponding contrasts; an asterisk indicates p < 0.050.
#> The lower panel displays the model coefficient for each contrast, together with its confidence interval and an approximate Cohen's d.
#> Each coefficient (indicated as Coef. 1, Coef. 2, and so forth) is horizontally aligned with the center of the corresponding comparison in the upper panel.The comparisons estimated by the coding derived from the hypothesis matrix.
The hypr package builds the same matrices from
hypotheses written as equations. hypr::hmat() returns the
hypothesis matrix in the format expected by hypotheses, and
hypr::cmat() the corresponding coding:
h <- hypr::hypr(TreatControl = (T1 + T2) / 2 ~ Control,
T2Control = T2 ~ Control,
levels = levels(trial$group))
trial_hypr <- trial
contrasts(trial_hypr$group) <- hypr::cmat(h)
fit_hypr <- lm(score ~ group, data = trial_hypr)
checked <- contrasts_onepred(fit_hypr, "group", hypotheses = hypr::hmat(h))
#> Contrast_1 estimates the declared hypothesis 'TreatControl': Mean(T1, T2) - Control.
#> Contrast_2 estimates the declared hypothesis 'T2Control': T2 - Control.Each declared hypothesis receives one of four results:
| Status | Meaning |
|---|---|
matches |
The coefficient estimates the declared comparison. |
rescaled |
It estimates the declared comparison multiplied by a positive factor. |
reversed |
It estimates the declared comparison with reversed sign. |
differs |
It estimates a different comparison, reported in the message. |
The scale of the declared weights does not matter:
c(-1, 0.5, 0.5) and c(-2, 1, 1) declare the
same comparison. A rescaled result is not an error, but it
tells how to read the coefficient. Under Helmert coding, for example,
the coefficients are fractions of the plain differences:
trial_helmert <- trial
contrasts(trial_helmert$group) <- contr.helmert(3)
fit_helmert <- lm(score ~ group, data = trial_helmert)
plain_differences <- rbind("T1-Control" = c(-1, 1, 0),
"T2-Mean(Control,T1)" = c(-0.5, -0.5, 1))
helmert <- contrasts_onepred(fit_helmert, "group", hypotheses = plain_differences)
#> Contrast_1 estimates the declared hypothesis 'T1-Control' (T1 - Control) multiplied by 1/2.
#> Contrast_2 estimates the declared hypothesis 'T2-Mean(Control,T1)' (T2 - Mean(Control, T1)) multiplied by 1/3.moplot_onepred(..., per_difference = TRUE) rescales the
lower panel so that it reports these plain differences.
For interactions, hypotheses is a named list with the
declared comparisons of one or more factors. 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 comparisons when each declared component does. Factors that
are not listed are not checked.
cells <- data.frame(
treatment = factor(rep(c("Low", "Medium", "High"), 2), levels = c("Low", "Medium", "High")),
context = factor(rep(c("Baseline", "Enhanced"), each = 3)),
mu = c(5, 7, 3, 6, 10, 5))
dat_int <- cells[rep(seq_len(6), each = 5), ]
dat_int$outcome <- dat_int$mu + rep(c(-1, -0.5, 0, 0.5, 1), 6)
intended_treatment <- rbind("Medium-Low" = c(Low = -1, Medium = 1, High = 0),
"High-Medium" = c(Low = 0, Medium = -1, High = 1))
intended_context <- rbind("Enhanced-Baseline" = c(Baseline = -1, Enhanced = 1))
contrasts(dat_int$treatment) <- MASS::ginv(intended_treatment)
contrasts(dat_int$context) <- MASS::contr.sdif(2)
model_int <- lm(outcome ~ treatment * context, data = dat_int)
decomposition <- contrasts_multpred(
model_int,
hypotheses = list(treatment = intended_treatment, context = intended_context),
methodological_note = FALSE
)
#> Variable treatment, contrast 1 estimates the declared hypothesis 'Medium-Low': Medium - Low.
#> Variable treatment, contrast 2 estimates the declared hypothesis 'High-Medium': High - Medium.
#> Variable context, contrast 1 estimates the declared hypothesis 'Enhanced-Baseline': Enhanced - Baseline.
attr(decomposition, "hypothesis_check")
#> Coefficient Hypothesis Status Ratio
#> 1 treatment1:context2-1 Medium-Low x Enhanced-Baseline matches 1
#> 2 treatment2:context2-1 High-Medium x Enhanced-Baseline matches 1moplot_multpred() accepts the same list and reports the
result in its caption. For a single predictor,
contrasts_onepred() and moplot_onepred() also
accept the list form, for example
hypotheses = list(group = intended).
MASS::ginv() or
hypr.