Skip to content

Adjusting for a covariate with ANCOVA

A covariate can sharpen a randomized comparison. It can't rescue groups that differ in ways you never measured, and it can answer a question nobody asked.

Applied ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Explain how ANCOVA gains precision in a randomized study
  • Check the homogeneous-slopes assumption
  • Recognize when adjusted means are extrapolation

Read first

01

What adjustment does

Read

ANCOVAANCOVACompares group means after adjusting for a continuous covariate, often a baseline measure. fits one line per group with a common slope, then compares the groups at the same covariate value. The results are adjusted means: what each group's mean would be if every group had the same covariate average.

In a randomized trial, the groups are alike on the covariate except by chance. Adjusting for a strong baseline measure removes variation from the outcome and narrows your interval.

02

Slide the covariate

Explore

Move one group along the covariate axis while the lines stay fixed. Watch the raw difference in means change while the adjusted difference holds still. Then push the groups so far apart they no longer overlap.

BExplorable · ANCOVA and adjusted means

When does adjusting for a covariate help, and when does it remove the effect you wanted?

What will the adjusted difference be?

1.5
How sure?
1.00
1.00
1.00

The covariate was measured

40
effect of interest0

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Predict what adjustment does

Predict

Predict first

Iris species differ by more than a centimeter in mean sepal length. They also differ greatly in petal width. What happens when you adjust sepal length for petal width?

Species still differ stronglyThe species difference almost vanishesThe species difference gets even larger
Reveal

The species difference almost vanishes: F(2, 146) = 0.07, p = .928. Before you conclude that species don't matter, look at the next step.

04

Where is the overlap?

Read

Setosa petals are all narrow and virginica petals all wide. Comparing the species "at the same petal width" asks about flowers that hardly exist. The model answers by extending lines beyond the data.

05

Check the slopes

Read
ANCOVARecorded · Python and R agreeRecorded 2026-11-25 · 35 values compared
R

F(2, 146) = 0.07, p = .928, η²p = .00

F (group)
0.0748
p
.928
R²
0.6694

Effect size

  • Partial η² (group) 0.0010
  • Partial ω² (group) −0.0125

Plots

Adjusted mean Sepal.Length by SpeciesWhat does the model predict for each group (and does the effect of one factor depend on another)?
View data
CI highCI lowAdjusted mean Sepal.LengthSpecies
6.2695.4915.880setosa
5.9635.6775.820versicolor
6.1745.4865.830virginica

Assumptions

  • Homogeneity of regression slopes — Group × covariate interaction: F(2, 144) = 1.66, p = .195.
  • Normality of residuals — Shapiro–Wilk on the residuals: p = .155.
  • Equal residual variances — Brown–Forsythe F = 5.27, p = .006 on the residuals.
  • Covariate independent of the grouping — Check by design: covariates measured before (or unaffected by) group membership.

ANCOVA (Type II/III sums of squares)

SourceSSdfMSFpη²p
Species0.034620.01730.0748.9280.0010
Petal.Width5.17615.17622.371< .0010.1329
Residual33.7801460.2314———

Adjusted means (covariates at their means)

SpeciesRaw meanAdjusted meanSECI lowCI high
setosa5.0065.8800.19695.4916.269
versicolor5.9365.8200.07235.6775.963
virginica6.5885.8300.17415.4866.174

Pairwise comparisons of adjusted means

ContrastDifferenceSEtp adj.CI lowCI high
setosa - versicolor0.06030.23040.2615.963−0.48530.6058
setosa - virginica0.05010.35820.1398.989−0.79810.8983
versicolor - virginica−0.01020.1663−0.0611.998−0.40400.3837
  • Model: Sepal.Length ~ Species + Petal.Width (sum-to-zero contrasts); adjusted means at the covariate means.
The exact R script · R R version 4.5.1 (2025-06-13)
# ANCOVA (group means adjusted for covariates)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.ancova 1.0.1 · spec 863bf1766509b8e6
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/iris.parquet", col_select = c("Sepal.Length", "Species", "Petal.Width")))
n_input <- nrow(df)
df[["Species"]] <- factor(df[["Species"]], levels = c("setosa", "versicolor", "virginica"))  # stored level order
df <- df[stats::complete.cases(df[c("Sepal.Length", "Species", "Petal.Width")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("Sepal.Length", "Species", "Petal.Width"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
y <- "Sepal.Length"
g <- "Species"
cov_cols <- c("Petal.Width")
covs <- paste0("c", seq_along(cov_cols))  # formula-safe names
cname <- stats::setNames(cov_cols, covs)
levels_g <- levels(df[[g]])
d <- data.frame(y = as.numeric(df[[y]]), g = factor(as.character(df[[g]]), levels = levels_g))
for (i in seq_along(covs)) d[[covs[i]]] <- as.numeric(df[[cov_cols[i]]])
k <- length(levels_g)
N <- nrow(d)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
# A constant outcome or covariate leaves nothing to test (the F ratios would be 0/0).
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = y)
for (i in seq_along(covs)) {
  if (length(unique(d[[covs[i]]])) < 2) cs_error("CS_E_CONSTANT", column = cov_cols[i])
}
if (N < k + length(covs) + 1) {  # the model needs at least one residual degree of freedom
  cs_error("CS_E_TOO_FEW_ROWS", what = "ANCOVA", min = k + length(covs) + 1, n = N)
}
conf <- 0.95
rhs <- paste("g +", paste(covs, collapse = " + "))
fit <- lm(stats::as.formula(paste("y ~", rhs)), data = d, contrasts = list(g = "contr.sum"))
if (anyNA(coef(fit))) cs_error("CS_E_COLLINEAR")  # e.g. a covariate fixed by the group
if (sum(residuals(fit)^2) <= 1e-12 * sum((d$y - mean(d$y))^2)) {  # an exact fit leaves no residual variation: every F ratio is undefined
  cs_error("CS_E_UNDEFINED", what = "ANCOVA", reason = "the model fits every value exactly, so there is no residual variation")
}
tab <- cs_anova_table(fit, 2)  # Type II = Type III without interactions
ss_resid <- sum(residuals(fit)^2)
df_resid <- fit$df.residual
grp <- tab[tab$term == "g", ]
eta_p_group <- grp$ss / (grp$ss + ss_resid)
omega_p_group <- grp$df * (grp$f - 1) / (grp$df * (grp$f - 1) + N)
# Homogeneity of slopes: add the group x covariate interactions and compare the models.
fit_int <- lm(stats::as.formula(paste("y ~", rhs, "+", paste(paste0("g:", covs), collapse = " + "))), data = d, contrasts = list(g = "contr.sum"))
if (fit_int$df.residual >= 1 && fit$df.residual - fit_int$df.residual >= 1) {
  cmp <- anova(fit, fit_int)
  f_slopes <- cmp$F[2]
  p_slopes <- cmp$`Pr(>F)`[2]
  df_slopes <- cmp$Df[2]
} else {  # too few rows for a separate slope in every group: the test is undefined (null in both engines)
  f_slopes <- NULL
  p_slopes <- NULL
  df_slopes <- NULL
  warnings <- c(warnings, cs_warning("CS_W_SMALL_SAMPLE", n = N, consequence = "the slopes can't be compared between groups."))
}

# %% Adjusted means (covariates at their means) and comparisons
adjust <- "tukey"
adj <- cs_emmeans(fit, d, "g", "g", covs, conf = conf)
comps <- if (TRUE) cs_emm_contrasts(fit, d, "g", "g", covs, adjust = adjust, conf = conf) else data.frame()

# %% Assumptions
assumptions <- list()
if (is.null(p_slopes)) {
  assumptions[[1]] <- list(key = "homogeneity", label = "Homogeneity of regression slopes", status = "info",
                           detail = "Too few rows to fit a separate slope in every group, so the slopes can't be compared.")
} else {
  assumptions[[1]] <- list(key = "homogeneity", label = "Homogeneity of regression slopes", status = if (p_slopes < 0.05) "warn" else "pass",
                           statistic = f_slopes, p = p_slopes,
                           detail = paste0(sprintf("Group × covariate interaction: F(%.0f, %.0f) = %.2f, %s", df_slopes, fit_int$df.residual, f_slopes, cs_fmt_p(p_slopes)),
                                           if (p_slopes < 0.05) "; the slopes differ, so adjusted differences depend on the covariate values." else "."))
}
res <- residuals(fit)
sw_p <- if (N >= 3 && N <= 5000) shapiro.test(res)$p.value else NULL
if (is.null(sw_p)) {
  assumptions[[2]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Too few (or too many) residuals for Shapiro–Wilk.")
} else {
  assumptions[[2]] <- list(key = "normality", label = "Normality of residuals", status = if (sw_p >= 0.05) "pass" else if (N < 60) "warn" else "info",
                           p = sw_p, detail = sprintf("Shapiro–Wilk on the residuals: %s.", cs_fmt_p(sw_p)))
}
z <- abs(res - ave(res, d$g, FUN = median))
if (min(table(d$g)) >= 2) {
  lev <- oneway.test(z ~ d$g, var.equal = TRUE)  # Brown-Forsythe on the residuals
  lev_f <- unname(lev$statistic)
  lev_p <- lev$p.value
  assumptions[[3]] <- list(key = "equal_variance", label = "Equal residual variances", status = if (lev_p < 0.05) "warn" else "pass",
                           statistic = lev_f, p = lev_p, detail = sprintf("Brown–Forsythe F = %.2f, %s on the residuals.", lev_f, cs_fmt_p(lev_p)))
} else {  # a group with a single value: Brown-Forsythe is undefined (oneway.test needs two values per group)
  lev_f <- NULL
  lev_p <- NULL
  assumptions[[3]] <- list(key = "equal_variance", label = "Equal residual variances", status = "info",
                           detail = "A group has a single value, so the residual variances can't be compared.")
}
assumptions[[4]] <- list(key = "independence", label = "Covariate independent of the grouping", status = "info",
                         detail = "Check by design: covariates measured before (or unaffected by) group membership.")

# %% Result
r2 <- summary(fit)$r.squared
values <- list(f_group = grp$f, df_group = grp$df, p_group = grp$p, eta_p_group = eta_p_group, omega_p_group = omega_p_group,
               ss_resid = ss_resid, df_resid = df_resid, r2 = r2, n = N, k = k, f_slopes = f_slopes, df_slopes = df_slopes, p_slopes = p_slopes,
               sw_p_resid = sw_p, levene_f = lev_f, levene_p = lev_p, group_name = g)
for (s in covs) {
  values[[sprintf("f[%s]", cname[[s]])]] <- tab$f[tab$term == s]
  values[[sprintf("p[%s]", cname[[s]])]] <- tab$p[tab$term == s]
  values[[sprintf("slope[%s]", cname[[s]])]] <- unname(coef(fit)[s])
}
raw <- tapply(d$y, d$g, mean)
for (i in seq_len(k)) {
  values[[sprintf("adj_mean[%s]", levels_g[i])]] <- adj$emm[i]
  values[[sprintf("raw_mean[%s]", levels_g[i])]] <- unname(raw[levels_g[i]])
}
for (i in seq_len(nrow(comps))) {
  values[[sprintf("diff[%s]", comps$contrast[i])]] <- comps$estimate[i]
  values[[sprintf("p_adj[%s]", comps$contrast[i])]] <- comps$p_adj[i]
}
term_order <- c("g", covs)
anova_rows <- lapply(term_order, function(t_) {
  r_ <- tab[tab$term == t_, ]
  list(term = if (t_ == "g") g else cname[[t_]], ss = r_$ss, df = r_$df, ms = r_$ss / r_$df, f = r_$f, p = r_$p, eta_p = r_$ss / (r_$ss + ss_resid))
})
anova_rows[[length(anova_rows) + 1]] <- list(term = "Residual", ss = ss_resid, df = df_resid, ms = ss_resid / df_resid)
tables <- list(
  list(key = "anova", title = "ANCOVA (Type II/III sums of squares)",
       columns = list(list(key = "term", label = "Source", type = "string"), list(key = "ss", label = "SS", type = "number"),
                      list(key = "df", label = "df", type = "number"), list(key = "ms", label = "MS", type = "number"),
                      list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"),
                      list(key = "eta_p", label = "η²p", type = "number")),
       rows = anova_rows),
  list(key = "emm", title = "Adjusted means (covariates at their means)",
       columns = list(list(key = "level", label = g, type = "string"), list(key = "raw", label = "Raw mean", type = "number"),
                      list(key = "emm", label = "Adjusted mean", type = "number"), list(key = "se", label = "SE", type = "number"),
                      list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")),
       rows = data.frame(level = levels_g, raw = unname(as.vector(raw)), emm = adj$emm, se = adj$se, ci_low = adj$ci_low, ci_high = adj$ci_high,
                         stringsAsFactors = FALSE))
)
if (nrow(comps) > 0) {
  tables[[3]] <- list(key = "posthoc", title = "Pairwise comparisons of adjusted means",
                      columns = list(list(key = "contrast", label = "Contrast", type = "string"), list(key = "estimate", label = "Difference", type = "number"),
                                     list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
                                     list(key = "p_adj", label = "p adj.", type = "pvalue"), list(key = "ci_low", label = "CI low", type = "number"),
                                     list(key = "ci_high", label = "CI high", type = "number")),
                      rows = comps[, c("contrast", "estimate", "se", "t", "p_adj", "ci_low", "ci_high")])
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
values$max_interaction_order <- 1
values$n_params <- length(coef(fit))
cs_publish(list(
  method = "anova.ancova",
  methodVersion = "1.0.1",
  title = "ANCOVA",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = N,
  summary = sprintf("Adjusted for %s: F(%.0f, %.0f) = %.2f, %s, partial η² = %.3f.", paste(cov_cols, collapse = ", "), grp$df, df_resid, grp$f,
                    cs_fmt_p(grp$p), eta_p_group),
  apa = sprintf("F(%.0f, %.0f) = %s, %s, η²p = %s", grp$df, df_resid, cs_fmt_num(grp$f), cs_fmt_p(grp$p), cs_fmt_num(eta_p_group, leading_zero = FALSE)),
  statistics = list(list(key = "f_group", label = "F (group)", value = grp$f), list(key = "p_group", label = "p", value = grp$p, format = "p"),
                    list(key = "r2", label = "R²", value = r2)),
  tables = tables,
  effectSizes = list(list(key = "eta_p_group", label = "Partial η² (group)", value = eta_p_group, method = "SS_group / (SS_group + SS_residual)"),
                     list(key = "omega_p_group", label = "Partial ω² (group)", value = omega_p_group, method = "df (F − 1) / (df (F − 1) + N)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Model: %s ~ %s + %s (sum-to-zero contrasts); adjusted means at the covariate means.", y, g, paste(cov_cols, collapse = " + "))),
  values = values,
  charts = list(cs_chart("adjusted-means", "emm-plot", sprintf("Adjusted mean %s by %s", y, g), list(
    x = cs_col(g, levels_g, "categorical", levels = levels_g),
    mean = cs_col(paste("Adjusted mean", y), adj$emm, "numeric"),
    low = cs_col("CI low", adj$ci_low, "numeric"),
    high = cs_col("CI high", adj$ci_high, "numeric"))))
))
Python

F(2, 146) = 0.07, p = .928, η²p = .00

F (group)
0.0748
p
.928
R²
0.6694

Effect size

  • Partial η² (group) 0.0010
  • Partial ω² (group) −0.0125

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Homogeneity of regression slopes — Group × covariate interaction: F(2, 144) = 1.66, p = .195.
  • Normality of residuals — Shapiro–Wilk on the residuals: p = .155.
  • Equal residual variances — Brown–Forsythe F = 5.27, p = .006 on the residuals.
  • Covariate independent of the grouping — Check by design: covariates measured before (or unaffected by) group membership.

ANCOVA (Type II/III sums of squares)

SourceSSdfMSFpη²p
Species0.034620.01730.0748.9280.0010
Petal.Width5.17615.17622.371< .0010.1329
Residual33.7801460.2314———

Adjusted means (covariates at their means)

SpeciesRaw meanAdjusted meanSECI lowCI high
setosa5.0065.8800.19695.4916.269
versicolor5.9365.8200.07235.6775.963
virginica6.5885.8300.17415.4866.174

Pairwise comparisons of adjusted means

ContrastDifferenceSEtp adj.CI lowCI high
setosa - versicolor0.06030.23040.2615.963−0.48530.6058
setosa - virginica0.05010.35820.1398.989−0.79810.8983
versicolor - virginica−0.01020.1663−0.0611.998−0.40400.3837
  • Model: Sepal.Length ~ Species + Petal.Width (sum-to-zero contrasts); adjusted means at the covariate means.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ANCOVA (group means adjusted for covariates)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.ancova 1.0.1 · spec 863bf1766509b8e6
# Dataset: iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats

import codesplash as cs
from codesplash.stats import anova as csa
from codesplash.stats import emm

# %% Data
df = pd.read_parquet("tests/parity/fixtures/iris.parquet", columns=["Sepal.Length", "Species", "Petal.Width"])
n_input = len(df)
df["Species"] = pd.Categorical(df["Species"], categories=["setosa", "versicolor", "virginica"])  # stored level order
df = df.dropna(subset=["Sepal.Length", "Species", "Petal.Width"])  # listwise deletion over the analysis columns
df["Species"] = df["Species"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["Sepal.Length", "Species", "Petal.Width"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
y, g = "Sepal.Length", "Species"
cov_cols = ["Petal.Width"]
covs = [f"c{i + 1}" for i in range(len(cov_cols))]  # formula-safe names
cname = dict(zip(covs, cov_cols))
levels = [str(x) for x in df[g].cat.categories]
d = pd.DataFrame({"y": df[y].to_numpy(dtype=float), "g": pd.Categorical(df[g].astype(str), categories=levels)})
for s, c in zip(covs, cov_cols):
    d[s] = df[c].to_numpy(dtype=float)
k, N = len(levels), len(d)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
# A constant outcome or covariate leaves nothing to test (the F ratios would be 0/0).
if d["y"].nunique() < 2:
    cs.cs_error("CS_E_CONSTANT", column=y)
for s, c in zip(covs, cov_cols):
    if d[s].nunique() < 2:
        cs.cs_error("CS_E_CONSTANT", column=c)
if N < k + len(covs) + 1:  # the model needs at least one residual degree of freedom
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="ANCOVA", min=k + len(covs) + 1, n=N)
conf = 0.95
rhs = "C(g, Sum) + " + " + ".join(covs)
fit = smf.ols("y ~ " + rhs, d).fit()
if np.linalg.matrix_rank(fit.model.exog) < fit.model.exog.shape[1]:  # e.g. a covariate fixed by the group
    cs.cs_error("CS_E_COLLINEAR")
if fit.ssr <= 1e-12 * fit.centered_tss:  # an exact fit leaves no residual variation: every F ratio is undefined
    cs.cs_error("CS_E_UNDEFINED", what="ANCOVA", reason="the model fits every value exactly, so there is no residual variation")
tab, ss_resid, df_resid = csa.anova_table(fit, 2)  # Type II = Type III without interactions
rows = {r["term"]: r for _, r in tab.iterrows()}
grp = rows["g"]
eta_p_group = grp["ss"] / (grp["ss"] + ss_resid)
omega_p_group = grp["df"] * (grp["f"] - 1) / (grp["df"] * (grp["f"] - 1) + N)
# Homogeneity of slopes: add the group × covariate interactions and compare the models.
fit_int = smf.ols("y ~ " + rhs + " + " + " + ".join(f"C(g, Sum):{s}" for s in covs), d).fit()
if fit_int.df_resid >= 1 and fit.df_resid - fit_int.df_resid >= 1:
    f_slopes, p_slopes, df_slopes = fit_int.compare_f_test(fit)
    f_slopes, p_slopes, df_slopes = float(f_slopes), float(p_slopes), float(df_slopes)
else:  # too few rows for a separate slope in every group: the test is undefined (null in both engines)
    f_slopes = p_slopes = df_slopes = None
    warnings.append(cs.cs_warning("CS_W_SMALL_SAMPLE", n=N, consequence="the slopes can't be compared between groups."))

# %% Adjusted means (covariates at their means) and comparisons
adjust = "tukey"
adj = emm.emmeans(fit, d, "g", ["g"], covs, conf=conf)
comps = emm.contrasts(fit, d, "g", ["g"], covs, adjust=adjust, conf=conf) if True else pd.DataFrame()

# %% Assumptions
assumptions = []
if p_slopes is None:
    assumptions.append({"key": "homogeneity", "label": "Homogeneity of regression slopes", "status": "info",
                        "detail": "Too few rows to fit a separate slope in every group, so the slopes can't be compared."})
else:
    assumptions.append({"key": "homogeneity", "label": "Homogeneity of regression slopes", "status": "warn" if p_slopes < 0.05 else "pass",
                        "statistic": f_slopes, "p": p_slopes,
                        "detail": f"Group × covariate interaction: F({df_slopes:.0f}, {fit_int.df_resid:.0f}) = {f_slopes:.2f}, {cs.fmt_p(p_slopes)}"
                        + ("; the slopes differ, so adjusted differences depend on the covariate values." if p_slopes < 0.05 else ".")})
resid = np.asarray(fit.resid, dtype=float)
sw_p = float(stats.shapiro(resid).pvalue) if 3 <= N <= 5000 else None
if sw_p is None:
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "info", "detail": "Too few (or too many) residuals for Shapiro–Wilk."})
else:
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "pass" if sw_p >= 0.05 else ("warn" if N < 60 else "info"),
                        "p": sw_p, "detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)}."})
groups_resid = [resid[(d["g"] == lv).to_numpy()] for lv in levels]
if min(len(x) for x in groups_resid) >= 2:
    lev = stats.levene(*groups_resid, center="median")
    lev_f, lev_p = float(lev.statistic), float(lev.pvalue)
    assumptions.append({"key": "equal_variance", "label": "Equal residual variances", "status": "warn" if lev_p < 0.05 else "pass",
                        "statistic": lev_f, "p": lev_p,
                        "detail": f"Brown–Forsythe F = {lev_f:.2f}, {cs.fmt_p(lev_p)} on the residuals."})
else:  # a group with a single value: Brown–Forsythe is undefined (R's convention: two values per group)
    lev_f = lev_p = None
    assumptions.append({"key": "equal_variance", "label": "Equal residual variances", "status": "info",
                        "detail": "A group has a single value, so the residual variances can't be compared."})
assumptions.append({"key": "independence", "label": "Covariate independent of the grouping", "status": "info",
                    "detail": "Check by design: covariates measured before (or unaffected by) group membership."})

# %% Result
values = {"f_group": grp["f"], "df_group": grp["df"], "p_group": grp["p"], "eta_p_group": eta_p_group, "omega_p_group": omega_p_group,
          "ss_resid": ss_resid, "df_resid": df_resid, "r2": float(fit.rsquared), "n": N, "k": k, "f_slopes": f_slopes,
          "df_slopes": df_slopes, "p_slopes": p_slopes, "sw_p_resid": sw_p, "levene_f": lev_f, "levene_p": lev_p,
          "group_name": g}
for s in covs:
    values[f"f[{cname[s]}]"] = rows[s]["f"]
    values[f"p[{cname[s]}]"] = rows[s]["p"]
    values[f"slope[{cname[s]}]"] = float(fit.params[s])
raw = d.groupby("g", observed=False)["y"].mean()
for lv, (_, e) in zip(levels, adj.iterrows()):
    values[f"adj_mean[{lv}]"] = e["emm"]
    values[f"raw_mean[{lv}]"] = float(raw[lv])
for _, c in comps.iterrows():
    values[f"diff[{c['contrast']}]"] = c["estimate"]
    values[f"p_adj[{c['contrast']}]"] = c["p_adj"]
anova_rows = [{"term": g if r["term"] == "g" else cname[r["term"]], "ss": r["ss"], "df": r["df"], "ms": r["ss"] / r["df"], "f": r["f"], "p": r["p"],
               "eta_p": r["ss"] / (r["ss"] + ss_resid)} for _, r in tab.iterrows()]
anova_rows.append({"term": "Residual", "ss": ss_resid, "df": df_resid, "ms": ss_resid / df_resid})
tables = [
    {"key": "anova", "title": "ANCOVA (Type II/III sums of squares)", "columns": [
        {"key": "term", "label": "Source", "type": "string"}, {"key": "ss", "label": "SS", "type": "number"},
        {"key": "df", "label": "df", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
        {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "eta_p", "label": "η²p", "type": "number"}], "rows": anova_rows},
    {"key": "emm", "title": "Adjusted means (covariates at their means)", "columns": [
        {"key": "level", "label": g, "type": "string"}, {"key": "raw", "label": "Raw mean", "type": "number"},
        {"key": "emm", "label": "Adjusted mean", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
        {"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}],
     "rows": [{"level": lv, "raw": float(raw[lv]), "emm": e["emm"], "se": e["se"], "ci_low": e["ci_low"], "ci_high": e["ci_high"]}
              for lv, (_, e) in zip(levels, adj.iterrows())]},
]
if len(comps):
    tables.append({"key": "posthoc", "title": "Pairwise comparisons of adjusted means", "columns": [
        {"key": "contrast", "label": "Contrast", "type": "string"}, {"key": "estimate", "label": "Difference", "type": "number"},
        {"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
        {"key": "p_adj", "label": "p adj.", "type": "pvalue"}, {"key": "ci_low", "label": "CI low", "type": "number"},
        {"key": "ci_high", "label": "CI high", "type": "number"}],
        "rows": comps[["contrast", "estimate", "se", "t", "p_adj", "ci_low", "ci_high"]].to_dict("records")})
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
values["max_interaction_order"] = 1
values["n_params"] = len(fit.params)
cs.publish({
    "method": "anova.ancova",
    "methodVersion": "1.0.1",
    "title": "ANCOVA",
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": N,
    "summary": f"Adjusted for {', '.join(cov_cols)}: F({grp['df']:.0f}, {df_resid:.0f}) = {grp['f']:.2f}, {cs.fmt_p(grp['p'])}, partial η² = {eta_p_group:.3f}.",
    "apa": f"F({grp['df']:.0f}, {df_resid:.0f}) = {cs.fmt_num(grp['f'])}, {cs.fmt_p(grp['p'])}, η²p = {cs.fmt_num(eta_p_group, leading_zero=False)}",
    "statistics": [{"key": "f_group", "label": "F (group)", "value": grp["f"]}, {"key": "p_group", "label": "p", "value": grp["p"], "format": "p"},
                   {"key": "r2", "label": "R²", "value": float(fit.rsquared)}],
    "tables": tables,
    "effectSizes": [{"key": "eta_p_group", "label": "Partial η² (group)", "value": eta_p_group, "method": "SS_group / (SS_group + SS_residual)"},
                    {"key": "omega_p_group", "label": "Partial ω² (group)", "value": omega_p_group, "method": "df (F − 1) / (df (F − 1) + N)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Model: {y} ~ {g} + {' + '.join(cov_cols)} (sum-to-zero contrasts); adjusted means at the covariate means."],
    "values": values,
    "charts": [cs.chart("adjusted-means", "emm-plot", f"Adjusted mean {y} by {g}", {
        "x": cs.col(g, levels, "categorical", levels=levels),
        "mean": cs.col(f"Adjusted mean {y}", adj["emm"].to_numpy(), "numeric"),
        "low": cs.col("CI low", adj["ci_low"].to_numpy(), "numeric"),
        "high": cs.col("CI high", adj["ci_high"].to_numpy(), "numeric")})],
})

ANCOVA assumes one common slope. CodeSplash tests that with a group × covariate term: F(2, 146) = 1.66, p = .195. If slopes differ, a single adjusted difference misleads, because the gap depends on where you measure it.

Note also Levene's check: p = .006. The residual spreads differ, so robust standard errors are worth a look.

06

Reflect on your design

Reflect

ANCOVA does well when the covariate is measured before treatment and strongly predicts the outcome. A covariate measured after treatment can be changed by the treatment, and adjusting for it removes part of the effect.

Think about a covariate you would add to a current analysis. Was it measured before the treatment could affect it?

07

Check your understanding

Checkpoint

Check yourself

Why add a baseline score as a covariate in a randomized trial?

Show the answer

Answer: a

Randomization already balances confounders on average. The gain from baseline adjustment is precision.

Check yourself

A training program improves fitness, and fitness improves test scores. You adjust for fitness measured after training. What happens to the estimated effect of training on test scores?

Show the answer

Answer: b

Fitness here is a mediator. Adjusting for it blocks the effect you want to measure.

Check yourself

The group × covariate term is strongly significant. What should you do?

Show the answer

Answer: b

Unequal slopes mean the group difference depends on the covariate. Show it across the range where you have data.

08

Do it in CodeSplash

In the app

Choose Outcome, Groups and one or more Covariates. Compare adjusted means adds pairwise comparisons. The card reports the homogeneous-slopes test as a check.

Python
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("iris.csv")
df = df.rename(columns={"Sepal.Length": "sepal", "Petal.Width": "petal"})
fit = smf.ols("sepal ~ petal + C(Species, Sum)", data=df).fit()
print(sm.stats.anova_lm(fit, typ=3))
R
# install.packages("car")
options(contrasts = c("contr.sum", "contr.poly"))
fit <- lm(Sepal.Length ~ Petal.Width + Species, data = iris)
car::Anova(fit, type = 3)
09

Recap

Recap
  • ANCOVA compares groups at the same covariate value, with a common slope.
  • In randomized studies it adds precision. In observational ones it doesn't remove unmeasured confounding.
  • Check the slopes, and check that the groups overlap on the covariate.

Concepts in this lesson