Skip to content

BCompare groups · anova.ancova

ANCOVA (group means adjusted for covariates)

Do group means differ after adjusting for one or more numeric covariates?

Analysis of covariance: compares groups on an outcome adjusted for numeric covariates (Type II/III sums of squares, which coincide without interactions), tests the homogeneity of the regression slopes, and reports adjusted (estimated marginal) means at the covariate means with pairwise comparisons.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Iris one covariate”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Iris one covariateiris · covariates: Petal.Width · group: Species · outcome: Sepal.Length
  • Mtcars two covariatesmtcars · covariates: hp, weight (1000 lbs) · group: cyl_f · outcome: mpg
  • Airquality missingairquality · covariates: Temp · group: month_f · outcome: Ozone
  • Degenerate constantiris · covariates: Petal.Width · group: Species · outcome: Sepal.Length
  • Degenerate single leveliris · covariates: Petal.Width · group: Species · outcome: Sepal.Length
  • Degenerate n3mtcars · covariates: hp, weight (1000 lbs) · group: cyl_f · outcome: mpg

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups
  • Association with covariates: linear / logistic regression · Statistics Guide · C — Test association
  • Normality (per group, differences or residuals) · Statistics Guide · Step 2 — Check assumptions
  • Linearity · Statistics Guide · Step 2 — Check assumptions
  • Interactions · Statistics Guide · Additional considerations
  • Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcomenumeric · 1 column
The numeric variable you are analyzing.
Groupscategorical / boolean · 1 column · 2–20 levels
The column whose levels define the groups to compare.
Covariatesnumeric · 1–5 columns
Numeric variables measured before (or unaffected by) the grouping.

Choices you make

posthoc

Compare adjusted meansdefault on

After the overall test, compare each pair of groups, with p-values adjusted for the number of comparisons.

Adjustmentdefault tukey

How pairwise p-values are corrected for multiple comparisons. Tukey suits all pairs of means; Holm works for any set.

  • Tukey(default) — Compares all pairs using the studentized range; the standard for all pairwise comparisons of means.
  • Holm — Controls the chance of any false positive; valid under any dependence, and better than Bonferroni.
  • Bonferroni — Multiplies each p by the number of comparisons; the plainest and strictest choice.
  • Šidák — A touch less strict than Bonferroni; exact when the comparisons are independent.
  • None — Reports raw p-values; use it for one planned comparison, or say plainly that results are exploratory.

hypothesis

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Homogeneity of regression slopes

    F test of the group × covariate interactions; ANCOVA assumes parallel slopes.

    • If violated → Regression with a group × covariate interaction — When slopes differ, the group difference depends on the covariate; model the interaction and read simple slopes and the Johnson–Neyman region instead of one adjusted difference. Changes the question: Group differences at chosen covariate values replace a single adjusted mean difference.
  • Normality of residuals

    Shapiro–Wilk on the model residuals.

  • Equal residual variances

    Brown–Forsythe test on the residuals across groups.

  • Covariate independent of the grouping

    Covariates should not be affected by the groups (e.g. measured at baseline).

What it reports

  • Tests: Difference in adjusted means
f_group
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
df_group
How much independent information is left to estimate variability after fitting the model.
p_group
How surprising your data would be if the null hypothesis were true, as a probability.
eta_p_group
Variance explained by an effect relative to that effect plus error, ignoring other effects in the model.
omega_p_group
A less biased version of η²; preferred for reporting how much variance an effect explains.
ss_resid
Total squared distance from a mean. ANOVA splits it between sources to show where the variation comes from.
df_resid
How much independent information is left to estimate variability after fitting the model.
r2
The share of the outcome's variance explained by the model, from 0 to 1.
n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
f_slopes
The ratio of explained to unexplained variance, used by ANOVA and regression tests.
df_slopes
How much independent information is left to estimate variability after fitting the model.
p_slopes
How surprising your data would be if the null hypothesis were true, as a probability.
sw_p_resid
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
levene_f
Tests whether groups have equal variances; the Brown–Forsythe version uses medians and resists skew.
levene_p
Tests whether groups have equal variances; the Brown–Forsythe version uses medians and resists skew.
group_name
Name of the grouping column whose covariate-adjusted means are compared.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.
max_interaction_order
The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
n_params
How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.

Per group, level or term: f[<covariate>], p[<covariate>], slope[<covariate>], adj_mean[<level>], raw_mean[<level>], diff[<a> - <b>], p_adj[<a> - <b>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, statsmodels, patsy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Tukey-adjusted p-values use the studentized range (scipy numeric integration vs R ptukey; ~1e-6).
Python

The exact script CodeSplash ran for example “Iris one covariate” · 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")})],
})
R

The exact script CodeSplash ran for example “Iris one covariate” · 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"))))
))

Sources

  • Huitema, B. E. (2011). The analysis of covariance and alternatives (2nd ed.). Wiley.
  • Searle, S. R., Speed, F. M., & Milliken, G. A. (1980). Population marginal means in the linear model. The American Statistician, 34, 216–221.

From the CodeSplash method registry · anova.ancova v1.0.1.