ANCOVA, Adjusting for a Covariate
Analysis of covariance, ANCOVA, compares group means after it accounts for a continuous covariate such as a baseline measurement. It is a linear model with one categorical predictor and one continuous predictor, the same machinery as multiple regression under a name from the experimental design literature.
This page fits ANCOVA to a mouse tumor study in which the arms already differed before the first dose. The raw comparison of final volumes finds nothing and the adjusted comparison finds a dose response. The page also states what you must believe about the study for the second answer to be the right one.
When to use it, and when not to
Section titled “When to use it, and when not to”ANCOVA has two uses, and they come with different guarantees.
- In a randomized trial, ANCOVA buys precision. Random allocation already makes the raw comparison unbiased, and a baseline that predicts the outcome only adds noise to it. Adjusting for that baseline removes the noise and usually narrows the interval of the treatment effect, so it is worth doing even when the arms look balanced.
- In a non-randomized comparison, ANCOVA adjusts for a measured confounder. The groups differ at baseline, the baseline drives the outcome, and the raw comparison mixes the two. The adjusted estimate is right only when the model is right: a straight-line carry-over from baseline, the same slope in every group, and no other difference between the groups that affects the outcome.
The example below is the second use. No output of the fitted model can confirm those three conditions, which is why a randomized design is worth more than any adjustment.
Do not adjust for a variable that the treatment can change. A covariate measured after the first dose sits downstream of the treatment, and adjusting for it removes part of the effect you want to estimate. A baseline recorded before treatment starts cannot carry part of the effect, but its time alone does not make adjustment right: a pretreatment variable can still be a collider.
Do not report one adjusted effect when the groups have different slopes. In that case the difference between arms depends on the baseline value, and the result to report is the interaction.
Get the data
Section titled “Get the data”Download tumor_study.csv into your working directory. The invented table has 90 rows, one per mouse, with 30 mice in each of three arms: control, low dose and high dose. The columns are mouse_id, arm, baseline_volume and final_volume, and both volumes are in mm³. Each mouse is one experimental unit.
Allocation was not random. Staff tended to dose the mice with the largest tumors first and to give them the higher dose, so the arms differ at baseline before the drug has done anything.
The values come from a simulation with a known answer. The final volume is 40 plus 0.85 times the baseline volume, plus the effect of the arm, plus noise with a standard deviation of 10 mm³. The effect of the arm is -12 mm³ for the low dose and -26 mm³ for the high dose.
The first block loads the table and defines a helper that later sections reuse. The helper prints each dosed arm minus control from a fitted model, with the standard error and the 95% confidence interval.
library(car)library(emmeans)library(ggplot2)
arms <- c("control", "low", "high")arm_colors <- c(control = "#3B6DB3", low = "#E9C46A", high = "#C1432B")tumor <- read.csv("tumor_study.csv")tumor$arm <- factor(tumor$arm, levels = arms)dir.create("outputs", showWarnings = FALSE)
#' Print each dosed arm minus control from a linear model.#'#' @param model A fitted lm that has the factor arm as a predictor.#' @param label A short name of the analysis for the printed lines.#' @return Invisibly, the coefficient table of the model.ReportArms <- function(model, label) { estimates <- summary(model)$coefficients interval <- confint(model) for (arm in c("low", "high")) { term <- paste0("arm", arm) cat(sprintf("%s, %s - control: %.2f, SE %.2f, 95%% CI [%.2f, %.2f]\n", label, arm, estimates[term, "Estimate"], estimates[term, "Std. Error"], interval[term, 1], interval[term, 2])) } invisible(estimates)}
print(head(tumor, 3)) mouse_id arm baseline_volume final_volume1 M001 control 104.8 138.12 M002 control 92.6 129.23 M003 control 105.5 135.6from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom scipy import statsfrom statsmodels.stats.anova import anova_lm
arms = ["control", "low", "high"]arm_colors = {"control": "#3B6DB3", "low": "#E9C46A", "high": "#C1432B"}tumor = pd.read_csv("tumor_study.csv")tumor["arm"] = pd.Categorical(tumor["arm"], categories=arms)output = Path("outputs")output.mkdir(exist_ok=True)
def report_arms(model, label): """Print each dosed arm minus control from a linear model.
Args: model: A fitted statsmodels OLS result with arm as a predictor. label: A short name of the analysis for the printed lines.
Returns: The confidence interval table of the model. """ interval = model.conf_int() for arm in ("low", "high"): term = f"arm[T.{arm}]" print(f"{label}, {arm} - control: {model.params[term]:.2f}, " f"SE {model.bse[term]:.2f}, 95% CI " f"[{interval.loc[term, 0]:.2f}, {interval.loc[term, 1]:.2f}]") return interval
print(tumor.head(3)) mouse_id arm baseline_volume final_volume0 M001 control 104.8 138.11 M002 control 92.6 129.22 M003 control 105.5 135.6Start with the unadjusted comparison
Section titled “Start with the unadjusted comparison”A one-way ANOVA of the final volume ignores the baseline. It is the analysis that a reader of the final measurements alone would run.
unadjusted <- lm(final_volume ~ arm, data = tumor)unadjusted_table <- anova(unadjusted)for (arm in arms) { cat(sprintf("%-8s mean final volume = %.2f\n", arm, mean(tumor$final_volume[tumor$arm == arm])))}cat(sprintf("One-way ANOVA: F(%d, %d) = %.2f, p = %.3f\n", unadjusted_table$Df[1], unadjusted_table$Df[2], unadjusted_table[["F value"]][1], unadjusted_table[["Pr(>F)"]][1]))ReportArms(unadjusted, "Unadjusted")control mean final volume = 125.92low mean final volume = 126.06high mean final volume = 122.20One-way ANOVA: F(2, 87) = 0.73, p = 0.487Unadjusted, low - control: 0.15, SE 3.64, 95% CI [-7.08, 7.37]Unadjusted, high - control: -3.72, SE 3.64, 95% CI [-10.94, 3.51]unadjusted = smf.ols("final_volume ~ arm", data=tumor).fit()unadjusted_table = anova_lm(unadjusted)for arm in arms: final_volume = tumor.loc[tumor["arm"] == arm, "final_volume"] print(f"{arm:<8} mean final volume = {final_volume.mean():.2f}")print(f"One-way ANOVA: F({unadjusted_table.loc['arm', 'df']:.0f}, " f"{unadjusted_table.loc['Residual', 'df']:.0f}) = " f"{unadjusted_table.loc['arm', 'F']:.2f}, " f"p = {unadjusted_table.loc['arm', 'PR(>F)']:.3f}")report_arms(unadjusted, "Unadjusted")control mean final volume = 125.92low mean final volume = 126.06high mean final volume = 122.20One-way ANOVA: F(2, 87) = 0.73, p = 0.487Unadjusted, low - control: 0.15, SE 3.64, 95% CI [-7.08, 7.37]Unadjusted, high - control: -3.72, SE 3.64, 95% CI [-10.94, 3.51]The three arms finish within 4 mm³ of each other, and the test gives F = 0.73 with p = 0.487. The intervals say the same in mm³: the high dose arm could end 10.94 mm³ below control or 3.51 mm³ above it.
As a description of where the arms ended, this result is correct. As an estimate of what the drug did, it fails, because the arms did not start at the same volume.
Compare the arms at baseline
Section titled “Compare the arms at baseline”The same one-way model, fitted to the baseline volume, shows how far apart the arms started. The range of each arm matters as much as its mean, because the adjustment later compares arms at one shared baseline value.
baseline_table <- anova(lm(baseline_volume ~ arm, data = tumor))for (arm in arms) { baseline <- tumor$baseline_volume[tumor$arm == arm] cat(sprintf("%-8s baseline mean = %.1f, range %.1f to %.1f\n", arm, mean(baseline), min(baseline), max(baseline)))}cat(sprintf("Baseline by arm: F(%d, %d) = %.2f, p = %.2g\n", baseline_table$Df[1], baseline_table$Df[2], baseline_table[["F value"]][1], baseline_table[["Pr(>F)"]][1]))control baseline mean = 99.6, range 73.5 to 119.8low baseline mean = 114.1, range 86.0 to 135.4high baseline mean = 128.2, range 109.1 to 157.6Baseline by arm: F(2, 87) = 43.12, p = 9.7e-14baseline_model = smf.ols("baseline_volume ~ arm", data=tumor).fit()baseline_table = anova_lm(baseline_model)for arm in arms: baseline = tumor.loc[tumor["arm"] == arm, "baseline_volume"] print(f"{arm:<8} baseline mean = {baseline.mean():.1f}, " f"range {baseline.min():.1f} to {baseline.max():.1f}")print(f"Baseline by arm: F({baseline_table.loc['arm', 'df']:.0f}, " f"{baseline_table.loc['Residual', 'df']:.0f}) = " f"{baseline_table.loc['arm', 'F']:.2f}, " f"p = {baseline_table.loc['arm', 'PR(>F)']:.2g}")control baseline mean = 99.6, range 73.5 to 119.8low baseline mean = 114.1, range 86.0 to 135.4high baseline mean = 128.2, range 109.1 to 157.6Baseline by arm: F(2, 87) = 43.12, p = 9.7e-14Mean baseline volume rises from 99.6 mm³ in control to 114.1 in the low dose arm and 128.2 in the high dose arm. If allocation were unrelated to baseline, an F statistic of 43.12 or larger would have a probability of 9.7e-14. Random allocation makes arms this far apart very unlikely, and the study description says why they are: the largest tumors were dosed first.
The high dose arm started 28.6 mm³ above control, and a larger tumor at baseline is a larger tumor at the end. That head start hides the effect of the drug in the unadjusted comparison.
The ranges overlap, and the adjustment depends on that overlap. All three arms have mice between 109.1 and 119.8 mm³. Outside that window at least one arm has no mice, so a comparison there extrapolates the fitted line of that arm.
Check the slopes
Section titled “Check the slopes”ANCOVA fits one slope for the baseline and lets only the intercept differ between arms. A model with an arm by baseline interaction gives each arm its own slope. An F test compares the two models, and the interaction coefficients estimate how far the slope of each dosed arm sits from the control slope.
additive <- lm(final_volume ~ arm + baseline_volume, data = tumor)separate_slopes <- lm(final_volume ~ arm * baseline_volume, data = tumor)slopes_test <- anova(additive, separate_slopes)cat(sprintf("Interaction: F(%d, %d) = %.2f, p = %.3f\n", slopes_test$Df[2], slopes_test$Res.Df[2], slopes_test$F[2], slopes_test[["Pr(>F)"]][2]))slope_interval <- confint(separate_slopes)for (arm in c("low", "high")) { term <- paste0("arm", arm, ":baseline_volume") cat(sprintf("%s slope minus control slope: %.2f [95%% CI %.2f, %.2f]\n", arm, coef(separate_slopes)[[term]], slope_interval[term, 1], slope_interval[term, 2]))}Interaction: F(2, 84) = 0.58, p = 0.560low slope minus control slope: 0.08 [95% CI -0.37, 0.54]high slope minus control slope: 0.23 [95% CI -0.20, 0.65]additive = smf.ols("final_volume ~ arm + baseline_volume", data=tumor).fit()separate_slopes = smf.ols("final_volume ~ arm * baseline_volume", data=tumor).fit()slopes_test = anova_lm(additive, separate_slopes)print(f"Interaction: F({slopes_test.loc[1, 'df_diff']:.0f}, " f"{slopes_test.loc[1, 'df_resid']:.0f}) = " f"{slopes_test.loc[1, 'F']:.2f}, " f"p = {slopes_test.loc[1, 'Pr(>F)']:.3f}")slope_interval = separate_slopes.conf_int()for arm in ("low", "high"): term = f"arm[T.{arm}]:baseline_volume" print(f"{arm} slope minus control slope: " f"{separate_slopes.params[term]:.2f} " f"[95% CI {slope_interval.loc[term, 0]:.2f}, " f"{slope_interval.loc[term, 1]:.2f}]")Interaction: F(2, 84) = 0.58, p = 0.560low slope minus control slope: 0.08 [95% CI -0.37, 0.54]high slope minus control slope: 0.23 [95% CI -0.20, 0.65]The test does not reject equal slopes, with F = 0.58 and p = 0.560. That result does not show that the slopes are equal. The intervals show what the data allow: the high dose slope could be 0.20 below the control slope or 0.65 above it. Thirty mice per arm cannot exclude a difference of that size, so the common slope stays an assumption that these data do not contradict. In this table the assumption is true by construction, because the simulation used a slope of 0.85 in every arm.
The figure draws the additive model: three parallel lines, one per arm. The dashed line marks the mean baseline of all 90 mice, where the adjusted means are read in a later section.
tumor$fitted_volume <- fitted(additive)slopes_plot <- ggplot(tumor, aes(baseline_volume, final_volume, color = arm)) + geom_point(alpha = 0.75, size = 1.8) + geom_line(aes(y = fitted_volume), linewidth = 1) + geom_vline(xintercept = mean(tumor$baseline_volume), linetype = "dashed", color = "grey40") + scale_color_manual(values = arm_colors) + labs(x = "Baseline tumor volume (mm³)", y = "Final tumor volume (mm³)", color = "Arm") + theme_minimal(base_size = 12)ggsave("outputs/ancova-slopes-r.png", slopes_plot, width = 5.6, height = 4.2, dpi = 150, bg = "white")
tumor["fitted_volume"] = additive.fittedvaluesslopes_figure, slopes_axes = plt.subplots(figsize=(5.6, 4.2))for arm in arms: rows = tumor[tumor["arm"] == arm].sort_values("baseline_volume") slopes_axes.scatter(rows["baseline_volume"], rows["final_volume"], s=18, alpha=0.75, color=arm_colors[arm], label=arm) slopes_axes.plot(rows["baseline_volume"], rows["fitted_volume"], color=arm_colors[arm], linewidth=1.6)slopes_axes.axvline(tumor["baseline_volume"].mean(), linestyle="--", color="grey")slopes_axes.set_xlabel("Baseline tumor volume (mm³)")slopes_axes.set_ylabel("Final tumor volume (mm³)")slopes_axes.legend(title="Arm", frameon=False)slopes_axes.spines[["top", "right"]].set_visible(False)slopes_figure.savefig(output / "ancova-slopes-python.png", dpi=150, bbox_inches="tight")plt.close(slopes_figure)
Fit the ANCOVA
Section titled “Fit the ANCOVA”The additive model from the last section is the ANCOVA. Anova() from car with type = 2, and anova_lm() with typ=2, test each term after the other term, so the arm is tested after the baseline. The default sequential table tests the terms in formula order, and arm + baseline_volume then gives a different arm test from baseline_volume + arm.
ancova_table <- Anova(additive, type = 2)for (term in c("arm", "baseline_volume")) { cat(sprintf("%s: F(%d, %d) = %.2f, p = %.2g\n", term, ancova_table[term, "Df"], ancova_table["Residuals", "Df"], ancova_table[term, "F value"], ancova_table[term, "Pr(>F)"]))}baseline_slope <- confint(additive)["baseline_volume", ]cat(sprintf("Baseline slope: %.3f [95%% CI %.3f, %.3f]\n", coef(additive)[["baseline_volume"]], baseline_slope[1], baseline_slope[2]))ReportArms(additive, "ANCOVA")arm: F(2, 86) = 32.97, p = 2.3e-11baseline_volume: F(1, 86) = 98.87, p = 5.9e-16Baseline slope: 0.863 [95% CI 0.691, 1.036]ANCOVA, low - control: -12.36, SE 2.79, 95% CI [-17.91, -6.81]ANCOVA, high - control: -28.40, SE 3.52, 95% CI [-35.40, -21.41]ancova_table = anova_lm(additive, typ=2)for term in ("arm", "baseline_volume"): print(f"{term}: F({ancova_table.loc[term, 'df']:.0f}, " f"{ancova_table.loc['Residual', 'df']:.0f}) = " f"{ancova_table.loc[term, 'F']:.2f}, " f"p = {ancova_table.loc[term, 'PR(>F)']:.2g}")baseline_slope = additive.conf_int().loc["baseline_volume"]print(f"Baseline slope: {additive.params['baseline_volume']:.3f} " f"[95% CI {baseline_slope[0]:.3f}, {baseline_slope[1]:.3f}]")report_arms(additive, "ANCOVA")arm: F(2, 86) = 32.97, p = 2.3e-11baseline_volume: F(1, 86) = 98.87, p = 5.9e-16Baseline slope: 0.863 [95% CI 0.691, 1.036]ANCOVA, low - control: -12.36, SE 2.79, 95% CI [-17.91, -6.81]ANCOVA, high - control: -28.40, SE 3.52, 95% CI [-35.40, -21.41]With baseline in the model, the arm term has F = 32.97 and p = 2.3e-11. The estimated slope is 0.863 mm³ of final volume per mm³ of baseline, and its interval, 0.691 to 1.036, covers the simulated 0.85. At an equal baseline the low dose arm ends 12.36 mm³ below control and the high dose arm 28.40 mm³ below. Both intervals cover the simulated effects of -12 and -26.
The adjustment recovers those effects because the simulation built the data from this model: one straight line, one slope for every arm, and no difference between the arms other than baseline and dose. Real non-randomized data give no such guarantee. If the mice that were dosed first also differed in growth rate, age or cage, the adjusted difference would carry those differences as well, and no output of the model would show it.
Read the adjusted means
Section titled “Read the adjusted means”An adjusted mean is the prediction of the model for one arm at a chosen baseline. emmeans() uses the mean baseline of all 90 mice. statsmodels has no equivalent of emmeans(), so the Python tab predicts each arm at that same baseline with get_prediction(). The raw means come from the unadjusted model, which gives each of them an interval from the pooled standard deviation.
raw_means <- as.data.frame(emmeans(unadjusted, ~ arm))adjusted <- emmeans(additive, ~ arm)adjusted_means <- as.data.frame(adjusted)cat(sprintf("Baseline volume of the adjusted means: %.2f\n", mean(tumor$baseline_volume)))for (row in seq_along(arms)) { cat(sprintf("%-8s raw %.2f [%.2f, %.2f], adjusted %.2f [%.2f, %.2f]\n", arms[row], raw_means$emmean[row], raw_means$lower.CL[row], raw_means$upper.CL[row], adjusted_means$emmean[row], adjusted_means$lower.CL[row], adjusted_means$upper.CL[row]))}Baseline volume of the adjusted means: 113.97control raw 125.92 [120.81, 131.03], adjusted 138.31 [134.02, 142.61]low raw 126.06 [120.95, 131.17], adjusted 125.95 [122.45, 129.46]high raw 122.20 [117.09, 127.31], adjusted 109.91 [105.63, 114.19]grid = pd.DataFrame({ "arm": pd.Categorical(arms, categories=arms), "baseline_volume": tumor["baseline_volume"].mean(),})raw_means = unadjusted.get_prediction(grid).summary_frame(alpha=0.05)adjusted_means = additive.get_prediction(grid).summary_frame(alpha=0.05)print("Baseline volume of the adjusted means: " f"{tumor['baseline_volume'].mean():.2f}")for row, arm in enumerate(arms): print(f"{arm:<8} raw {raw_means.loc[row, 'mean']:.2f} " f"[{raw_means.loc[row, 'mean_ci_lower']:.2f}, " f"{raw_means.loc[row, 'mean_ci_upper']:.2f}], " f"adjusted {adjusted_means.loc[row, 'mean']:.2f} " f"[{adjusted_means.loc[row, 'mean_ci_lower']:.2f}, " f"{adjusted_means.loc[row, 'mean_ci_upper']:.2f}]")Baseline volume of the adjusted means: 113.97control raw 125.92 [120.81, 131.03], adjusted 138.31 [134.02, 142.61]low raw 126.06 [120.95, 131.17], adjusted 125.95 [122.45, 129.46]high raw 122.20 [117.09, 127.31], adjusted 109.91 [105.63, 114.19]The raw means span 3.86 mm³ and their intervals overlap almost completely. The adjusted means fall from 138.31 mm³ in control to 125.95 at the low dose and 109.91 at the high dose.
Each adjusted mean is a prediction for mice with a baseline of 113.97 mm³. For control that value is above the arm’s own mean baseline of 99.6, so the adjusted mean sits above the raw mean. For the high dose arm it is below the mean baseline of 128.2, so the adjusted mean sits below the raw mean. Report the baseline value with the adjusted means. A different value moves all three means by the same amount and leaves their differences unchanged.
The figure puts the two sets of means side by side, each with its 95% confidence interval.
raw_means$kind <- "Raw mean"adjusted_means$kind <- "Adjusted for baseline"means_table <- rbind(raw_means, adjusted_means)means_table$kind <- factor(means_table$kind, levels = c("Raw mean", "Adjusted for baseline"))means_plot <- ggplot(means_table, aes(arm, emmean, color = arm)) + geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.15) + geom_point(size = 3.2) + facet_wrap(~ kind) + scale_color_manual(values = arm_colors, guide = "none") + labs(x = NULL, y = "Final tumor volume (mm³)") + theme_minimal(base_size = 12)ggsave("outputs/ancova-means-r.png", means_plot, width = 5.8, height = 3.8, dpi = 150, bg = "white")
panels = [("Raw mean", raw_means), ("Adjusted for baseline", adjusted_means)]means_figure, means_axes = plt.subplots(1, 2, figsize=(5.8, 3.8), sharey=True)for axes, (title, means) in zip(means_axes, panels): for row, arm in enumerate(arms): center = means.loc[row, "mean"] below = center - means.loc[row, "mean_ci_lower"] above = means.loc[row, "mean_ci_upper"] - center axes.errorbar(row, center, yerr=[[below], [above]], fmt="o", color=arm_colors[arm], capsize=3) axes.set_xticks(range(len(arms)), arms) axes.set_title(title, fontsize=11) axes.spines[["top", "right"]].set_visible(False)means_axes[0].set_ylabel("Final tumor volume (mm³)")means_figure.savefig(output / "ancova-means-python.png", dpi=150, bbox_inches="tight")plt.close(means_figure)
Compare each pair of arms
Section titled “Compare each pair of arms”pairs() takes the adjusted means and returns every pairwise difference. With reverse = TRUE each contrast is the higher dose minus the lower one, so a negative value is a smaller tumor. emmeans applies the Tukey method to the three contrasts, in the p-values and, through confint(), in the intervals.
statsmodels has pairwise_tukeyhsd(), but it takes a response and a group label and accepts no covariate. The Python tab therefore builds each contrast with t_test() and takes the Tukey p-value and interval from the studentized range distribution in SciPy, which is the calculation that emmeans makes.
contrasts <- pairs(adjusted, reverse = TRUE)contrast_tests <- as.data.frame(contrasts)contrast_intervals <- as.data.frame(confint(contrasts))p_text <- ifelse(contrast_tests$p.value < 1e-4, "< 0.0001", sprintf("= %.4f", contrast_tests$p.value))for (row in seq_len(nrow(contrast_tests))) { cat(sprintf("%s: %.2f [95%% CI %.2f, %.2f], Tukey p %s\n", contrast_tests$contrast[row], contrast_tests$estimate[row], contrast_intervals$lower.CL[row], contrast_intervals$upper.CL[row], p_text[row]))}low - control: -12.36 [95% CI -19.02, -5.70], Tukey p < 0.0001high - control: -28.40 [95% CI -36.79, -20.01], Tukey p < 0.0001high - low: -16.04 [95% CI -22.67, -9.41], Tukey p < 0.0001# Weights on the intercept, the low arm, the high arm and the baseline.contrasts = { "low - control": [0, 1, 0, 0], "high - control": [0, 0, 1, 0], "high - low": [0, -1, 1, 0],}residual_df = additive.df_residcritical = stats.studentized_range.ppf(0.95, len(arms), residual_df)for label, weights in contrasts.items(): test = additive.t_test(weights) estimate = test.effect.item() margin = critical / np.sqrt(2) * test.sd.item() p_tukey = stats.studentized_range.sf( abs(test.tvalue.item()) * np.sqrt(2), len(arms), residual_df) p_text = "< 0.0001" if p_tukey < 1e-4 else f"= {p_tukey:.4f}" print(f"{label}: {estimate:.2f} [95% CI {estimate - margin:.2f}, " f"{estimate + margin:.2f}], Tukey p {p_text}")low - control: -12.36 [95% CI -19.02, -5.70], Tukey p < 0.0001high - control: -28.40 [95% CI -36.79, -20.01], Tukey p < 0.0001high - low: -16.04 [95% CI -22.67, -9.41], Tukey p < 0.0001The two tabs print the same estimates and intervals. The Tukey intervals are wider than the single-comparison intervals of the ANCOVA fit above, -19.02 to -5.70 against -17.91 to -6.81 for the low dose, because the three Tukey intervals hold 95% coverage jointly. All three intervals exclude zero, and the high dose arm ends 16.04 mm³ below the low dose arm at an equal baseline.
The code prints a p-value below 0.0001 as a bound, as the emmeans table does. A tail probability that small comes from numerical integration of the studentized range distribution, and its digits are not reliable that far out.
Change scores and Lord’s paradox
Section titled “Change scores and Lord’s paradox”A common alternative subtracts the baseline from the final volume and compares the change between arms. That analysis is the same linear model with the baseline slope fixed at 1.
tumor$change <- tumor$final_volume - tumor$baseline_volumechange_score <- lm(change ~ arm, data = tumor)ReportArms(change_score, "Change score")ReportArms(additive, "ANCOVA")Change score, low - control: -14.34, SE 2.51, 95% CI [-19.34, -9.34]Change score, high - control: -32.31, SE 2.51, 95% CI [-37.31, -27.31]ANCOVA, low - control: -12.36, SE 2.79, 95% CI [-17.91, -6.81]ANCOVA, high - control: -28.40, SE 3.52, 95% CI [-35.40, -21.41]tumor["change"] = tumor["final_volume"] - tumor["baseline_volume"]change_score = smf.ols("change ~ arm", data=tumor).fit()report_arms(change_score, "Change score")report_arms(additive, "ANCOVA")Change score, low - control: -14.34, SE 2.51, 95% CI [-19.34, -9.34]Change score, high - control: -32.31, SE 2.51, 95% CI [-37.31, -27.31]ANCOVA, low - control: -12.36, SE 2.79, 95% CI [-17.91, -6.81]ANCOVA, high - control: -28.40, SE 3.52, 95% CI [-35.40, -21.41]Three analyses of the same 90 mice give three answers for the high dose: -3.72 mm³ unadjusted, -32.31 as a change score and -28.40 from ANCOVA. They differ in what they assume about the baseline. The unadjusted comparison gives it a slope of 0, the change score gives it a slope of 1, and ANCOVA estimates the slope, here 0.863.
When groups differ at baseline, the change score and ANCOVA can disagree, and the data cannot say which is right. ANCOVA is right if mice with the same baseline would have ended at the same volume without treatment, whichever arm they were in. The change score is right if the arms would have grown by the same amount without treatment. Neither condition can be tested in the table. This disagreement is Lord’s paradox.
In this table ANCOVA is closer to the simulated effects, and the change score interval for the high dose, -37.31 to -27.31, misses -26. The only reason is that the simulation built the data from the ANCOVA model.
In a randomized trial the paradox goes away. The arms share one expected baseline, so the unadjusted comparison, the change score and ANCOVA all estimate the same treatment effect and differ only in precision. ANCOVA is usually the most precise of the three, and its advantage over the change score grows as the slope moves away from 1. Vickers and Altman, cited below, work through that comparison for a trial.
This table cannot show that advantage. Here the change score has the smaller standard errors, 2.51 against 2.79 and 3.52 for ANCOVA. The baseline difference between the arms costs ANCOVA precision, because arm and baseline are correlated and the model must separate them. The high dose arm, which started furthest from control, pays the most.
Mistakes to avoid
Section titled “Mistakes to avoid”- Adjusting for a covariate that the treatment changed removes part of the treatment effect. Use a baseline recorded before the first dose.
- A nonsignificant interaction test is weak support for a common slope. Read the interval of the slope difference, here -0.20 to 0.65 for the high dose, and look at the scatter plot.
- An adjusted mean outside the baseline range of an arm is an extrapolation. Here the shared baseline of 113.97 mm³ lies inside all three ranges, but less than 5 mm³ above the smallest tumor in the high dose arm.
- A p-value of 2.3e-11 after adjustment does not show that the drug works in a non-randomized study. It shows that arms with an equal baseline differ in final volume. Whether the dose is the cause depends on what else differed between the arms.
- The same structure appears in omics data when batch is confounded with condition. A model can separate the two only where batches and conditions overlap, and a design that balances batch across conditions removes the problem before the analysis.
Scientific references
Section titled “Scientific references”Fox and Weisberg, 2019, describe the car functions in An R Companion to Applied Regression.
The emmeans package by Lenth and Piaskowski computes estimated marginal means.
Lord, 1967 describes the paradox in which a change score and a covariate adjustment give different answers for two groups that differ at baseline.
Vickers and Altman, 2001 compare the analysis of follow-up scores, change scores and analysis of covariance in randomized trials with a baseline measurement.
Further reading
Section titled “Further reading”The emmeans basics vignette explains how a reference grid defines an adjusted mean. Its treatment of covariates applies directly to the means at the shared baseline on this page.
The emmeans comparisons vignette covers pairs() and the multiplicity adjustments that it offers besides Tukey.
The multiple regression page covers the linear model behind ANCOVA, and the ANOVA page covers the one-way comparison that this page starts from. The assumption checks page shows how to inspect the residuals of a model like this one.