Skip to content

Two factors at once: main effects and interactions

A factorial design tests whether one factor's effect depends on the other. Read the interaction first, because it changes what the main effects mean.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Separate main effects from an interaction in a table of means
  • Read a two-way ANOVA table, starting with the interaction
  • Explain when Type II and Type III sums of squares differ

Read first

01

One study, three questions

Read

ToothGrowth crossed two supplements with three doses: six cells of 10 animals each. One experiment asks three questions:

  1. Does supplement matter, averaging over dose? That's a main effectMain effectThe average effect of one factor across the levels of the others..
  2. Does dose matter, averaging over supplement? Another main effect.
  3. Does supplement's effect depend on the dose? That's the interactionInteractionWhen the effect of one predictor depends on the level of another..

Lines that stay parallel on an interaction plot mean no interaction. Lines that converge or cross mean the effect of one factor changes with the other.

02

Make an interaction

Explore

Change the cell means until the lines cross, then until they are parallel. Watch the main effects shrink while the interaction grows. Can you make a large interaction with zero main effects?

DExplorable · Interactions and simple slopes

When the effect of x depends on a moderator, where is it actually different from zero?

What is the slope of x at this moderator value?

0.0
How sure?
0.50
120
0.0

Centering: with a mean far from zero, the coefficient on x describes a moderator value no one has.

1.0
no effectJ–NJ–N

Where the band excludes zero, the slope of x is significant at that moderator value. Johnson–Neyman (J–N) marks the boundaries.

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 the table

Predict

Predict first

Doses range from low to high, and tooth length changes a lot with dose. Which term do you expect to have the largest F?

Dose is largestSupplement is largestThe interaction is largest
Reveal

Dose: F(2, 54) = 92.0. Supplement has F = 15.6, and the interaction F = 4.11.

04

Read the interaction first

Read
Factorial ANOVA (supp × dose_f)Recorded · Python and R agreeRecorded 2026-11-25 · 65 values compared
R

interaction: F(2, 54) = 4.11, p = .022

R²
0.7937
Residual df
54

Effect size

  • Partial η² (supp) 0.2238
  • Partial η² (dose_f) 0.7731
  • Partial η² (supp × dose_f) 0.1320

Plots

Estimated marginal means of lenWhat does the model predict for each group (and does the effect of one factor depend on another)?
View data
CI highCI lowMean lendose_fsupp
15.53210.92813.2300.5OJ
10.2825.6787.9800.5VC
25.00220.39822.7001OJ
19.07214.46816.7701VC
28.36223.75826.0602OJ
28.44223.83826.1402VC

Assumptions

  • Normality of residuals — Shapiro–Wilk on the residuals: p = .669.
  • Equal variances across cells — Brown–Forsythe F = 1.71, p = .148 across 6 cells.
  • Balanced design — 6 cells with 10 observations each.

ANOVA (Type II sums of squares)

SourceSSdfMSFpη²pω²p
supp205.351205.3515.572< .0010.22380.1954
dose_f2426.4321213.2292.000< .0010.77310.7521
supp × dose_f108.32254.1604.107.0220.13200.0938
Residual712.115413.187————

Estimated marginal means

FactorLevelEMMSECI lowCI high
suppOJ20.6630.663019.33421.993
suppVC16.9630.663015.63418.293
dose_f0.510.6050.81208.97712.233
dose_f119.7350.812018.10721.363
dose_f226.1000.812024.47227.728

Pairwise comparisons of marginal means (Holm adjustment)

FactorContrastDifferenceSEtp adj.CI lowCI high
suppOJ - VC3.7000.93763.946< .0011.8205.580
dose_f0.5 - 1−9.1301.148−7.951< .001−11.432−6.828
dose_f0.5 - 2−15.4951.148−13.493< .001−17.797−13.193
dose_f1 - 2−6.3651.148−5.543< .001−8.667−4.063

Simple effects of supp within dose_f

EffectFdf1df2p
supp | dose_f=0.510.451154.002
supp | dose_f=113.333154< .001
supp | dose_f=20.0024154.961

Pairwise comparisons of supp within dose_f

WithinContrastDifferenceSEtp adj.CI lowCI high
dose_f=0.5OJ - VC5.2501.6243.233.0021.9948.506
dose_f=1OJ - VC5.9301.6243.651< .0012.6749.186
dose_f=2OJ - VC−0.08001.624−0.0493.961−3.3363.176
  • Model: len ~ supp * dose_f with sum-to-zero contrasts; marginal means weight the cells equally.
The exact R script · R R version 4.5.1 (2025-06-13)
# Factorial ANOVA (two or three between factors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.factorial 1.0.1 · spec 1dc19eb9e06d66ca
# Dataset: toothgrowth (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/toothgrowth.parquet", col_select = c("len", "supp", "dose_f")))
n_input <- nrow(df)
df[["supp"]] <- factor(df[["supp"]], levels = c("OJ", "VC"))  # stored level order
df[["dose_f"]] <- factor(df[["dose_f"]], levels = c("0.5", "1", "2"))  # stored level order
df <- df[stats::complete.cases(df[c("len", "supp", "dose_f")]), , 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("len", "supp", "dose_f"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
y <- "len"
factor_cols <- c("supp", "dose_f")
safe <- paste0("f", seq_along(factor_cols))  # formula-safe names
name <- stats::setNames(factor_cols, safe)
d <- data.frame(y = as.numeric(df[[y]]))
for (i in seq_along(safe)) {
  d[[safe[i]]] <- factor(as.character(df[[factor_cols[i]]]), levels = levels(df[[factor_cols[i]]]))
  if (nlevels(d[[safe[i]]]) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = factor_cols[i], min = 2, k = nlevels(d[[safe[i]]]))
}
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = y)  # a constant outcome leaves nothing to test (the F ratios would be 0/0)
cells <- table(d[safe])
if (any(cells == 0)) {
  idx <- which(cells == 0, arr.ind = TRUE)
  empty <- apply(idx, 1, function(r) paste(vapply(seq_along(r), function(j) dimnames(cells)[[j]][r[j]], ""), collapse = "/"))
  stop(sprintf("Every combination of factor levels needs data; empty cells: %s", paste(head(empty, 5), collapse = ", ")))
}
if (nrow(d) < length(cells) + 1) {  # one value per cell leaves no residual degrees of freedom
  cs_error("CS_E_TOO_FEW_ROWS", what = "Factorial ANOVA", min = length(cells) + 1, n = nrow(d))
}
ss_cells <- sum((d$y - ave(d$y, interaction(d[safe], drop = TRUE)))^2)
if (ss_cells <= 1e-12 * sum((d$y - mean(d$y))^2)) {  # no variation inside the cells: every F ratio is undefined
  cs_error("CS_E_UNDEFINED", what = "Factorial ANOVA", reason = sprintf("%s does not vary within any cell", y))
}
ss_type <- "2"
conf <- 0.95
alpha <- 1 - conf
# Sum-to-zero contrasts so Type III tests are meaningful; Types I/II do not depend on them.
fit <- lm(stats::as.formula(paste("y ~", paste(safe, collapse = " * "))), data = d,
          contrasts = stats::setNames(rep(list("contr.sum"), length(safe)), safe))
tab <- cs_anova_table(fit, as.integer(ss_type))
ss_resid <- sum(residuals(fit)^2)
df_resid <- fit$df.residual
N <- nrow(d)
term_label <- function(term) paste(name[strsplit(term, ":", fixed = TRUE)[[1]]], collapse = " × ")
terms <- data.frame(term = vapply(tab$term, term_label, ""), key = tab$term, ss = tab$ss, df = tab$df, ms = tab$ss / tab$df,
                    f = tab$f, p = tab$p, stringsAsFactors = FALSE)
terms$eta_p <- terms$ss / (terms$ss + ss_resid)
terms$omega_p <- terms$df * (terms$f - 1) / (terms$df * (terms$f - 1) + N)
# report terms in the Python/patsy order (main effects, then interactions by order)
terms <- terms[order(lengths(strsplit(terms$key, ":", fixed = TRUE)), match(terms$key, tab$term)), ]
rownames(terms) <- NULL
by_key <- function(k) terms[terms$key == k, ]
r2 <- summary(fit)$r.squared

# %% Estimated marginal means and comparisons
adjust <- "holm"
emms <- data.frame()
comps <- data.frame()
for (s in safe) {
  e <- cs_emmeans(fit, d, s, safe, character(0), conf = conf)
  emms <- rbind(emms, data.frame(factor = name[[s]], level = e$level, emm = e$emm, se = e$se, ci_low = e$ci_low, ci_high = e$ci_high,
                                 stringsAsFactors = FALSE))
  if (TRUE) {
    cc <- cs_emm_contrasts(fit, d, s, safe, character(0), adjust = adjust, conf = conf)
    comps <- rbind(comps, data.frame(factor = name[[s]], contrast = cc$contrast, estimate = cc$estimate, se = cc$se, df = cc$df, t = cc$t,
                                     p_adj = cc$p_adj, ci_low = cc$ci_low, ci_high = cc$ci_high, stringsAsFactors = FALSE))
  }
}
mode <- "always"
want_simple <- mode == "always" || (mode == "auto" && by_key("f1:f2")$p < alpha)
simple <- data.frame()
simple_pairs <- data.frame()
if (want_simple) {
  j <- cs_emm_joint_test(fit, d, "f1", safe, character(0), by = "f2")
  simple <- data.frame(effect = sprintf("%s | %s=%s", name[["f1"]], name[["f2"]], j$by), f = j$f, df1 = j$df1, df2 = j$df2, p = j$p,
                       stringsAsFactors = FALSE)
  cc <- cs_emm_contrasts(fit, d, "f1", safe, character(0), by = "f2", adjust = adjust, conf = conf)
  simple_pairs <- data.frame(within = sprintf("%s=%s", name[["f2"]], cc$by), contrast = cc$contrast, estimate = cc$estimate, se = cc$se,
                             t = cc$t, p_adj = cc$p_adj, ci_low = cc$ci_low, ci_high = cc$ci_high, stringsAsFactors = FALSE)
}
cell_emm <- cs_emmeans(fit, d, "f1", safe, character(0), by = "f2", conf = conf)

# %% Assumptions
assumptions <- list()
res <- residuals(fit)
sw_p <- if (length(res) >= 3 && length(res) <= 5000) shapiro.test(res)$p.value else NULL
if (is.null(sw_p)) {
  assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Too few (or too many) residuals for Shapiro–Wilk.")
} else {
  bad <- sw_p < 0.05
  assumptions[[1]] <- list(key = "normality", label = "Normality of residuals",
                           status = if (bad) (if (N < 60) "warn" else "info") else "pass", p = sw_p,
                           detail = paste0(sprintf("Shapiro–Wilk on the residuals: %s", cs_fmt_p(sw_p)),
                                           if (bad && N < 60) "; consider a transformation or a robust method."
                                           else if (bad) "; the F tests are robust with this sample size." else "."))
}
cell <- interaction(d[safe], drop = TRUE, lex.order = TRUE)
z <- abs(d$y - ave(d$y, cell, FUN = median))
if (min(table(cell)) >= 2) {
  lev <- oneway.test(z ~ cell, var.equal = TRUE)  # Brown-Forsythe across cells
  lev_f <- unname(lev$statistic)
  lev_p <- lev$p.value
  assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances across cells", status = if (lev_p < 0.05) "warn" else "pass",
                           statistic = lev_f, p = lev_p, detail = sprintf("Brown–Forsythe F = %.2f, %s across %d cells.", lev_f, cs_fmt_p(lev_p), nlevels(cell)))
} else {  # a cell with a single value: Brown-Forsythe is undefined (oneway.test needs two values per cell)
  lev_f <- NULL
  lev_p <- NULL
  assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances across cells", status = "info",
                           detail = "A cell has a single value, so the variances can't be compared across cells.")
}
sizes <- as.vector(cells)
balanced <- min(sizes) == max(sizes)
assumptions[[3]] <- list(key = "balance", label = "Balanced design", status = if (balanced) "pass" else "info",
                         detail = if (balanced) sprintf("%d cells with %d observations each.", length(sizes), min(sizes))
                                  else sprintf("Cell sizes range from %d to %d; Type %s sums of squares are used.", min(sizes), max(sizes), ss_type))

# %% Result
values <- list(ss_resid = ss_resid, df_resid = df_resid, r2 = r2, n = N, n_cells = length(sizes), min_cell = min(sizes), max_cell = max(sizes),
               sw_p_resid = sw_p, levene_f = lev_f, levene_p = lev_p, factor_a = name[["f1"]], factor_b = name[["f2"]],
               ss_type = c("1" = "I", "2" = "II", "3" = "III")[[ss_type]])
for (pair in list(c("a", "f1"), c("b", "f2"), c("ab", "f1:f2"))) {
  t_ <- by_key(pair[2])
  values[[paste0("f_", pair[1])]] <- t_$f
  values[[paste0("df_", pair[1])]] <- t_$df
  values[[paste0("p_", pair[1])]] <- t_$p
  values[[paste0("eta_p_", pair[1])]] <- t_$eta_p
}
for (i in seq_len(nrow(terms))) {
  for (k_ in c("f", "p", "df", "ss", "eta_p", "omega_p")) values[[sprintf("%s[%s]", k_, terms$term[i])]] <- terms[[k_]][i]
}
for (i in seq_len(nrow(emms))) values[[sprintf("emm[%s: %s]", emms$factor[i], emms$level[i])]] <- emms$emm[i]
for (i in seq_len(nrow(comps))) {
  values[[sprintf("diff[%s: %s]", comps$factor[i], comps$contrast[i])]] <- comps$estimate[i]
  values[[sprintf("p_adj[%s: %s]", comps$factor[i], comps$contrast[i])]] <- comps$p_adj[i]
}
for (i in seq_len(nrow(simple))) {
  values[[sprintf("simple_f[%s]", simple$effect[i])]] <- simple$f[i]
  values[[sprintf("simple_p[%s]", simple$effect[i])]] <- simple$p[i]
}
anova_rows <- lapply(seq_len(nrow(terms)), function(i) as.list(terms[i, c("term", "ss", "df", "ms", "f", "p", "eta_p", "omega_p")]))
anova_rows[[length(anova_rows) + 1]] <- list(term = "Residual", ss = ss_resid, df = df_resid, ms = ss_resid / df_resid)
adj_label <- c(tukey = "Tukey", holm = "Holm", bonferroni = "Bonferroni", sidak = "Šidák", scheffe = "Scheffé", none = "no")[[adjust]]
tables <- list(
  list(key = "anova", title = sprintf("ANOVA (Type %s sums of squares)", values$ss_type),
       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"), list(key = "omega_p", label = "ω²p", type = "number")),
       rows = anova_rows),
  list(key = "emm", title = "Estimated marginal means",
       columns = list(list(key = "factor", label = "Factor", type = "string"), list(key = "level", label = "Level", type = "string"),
                      list(key = "emm", label = "EMM", 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 = emms)
)
if (nrow(comps) > 0) {
  tables[[length(tables) + 1]] <- list(key = "posthoc", title = sprintf("Pairwise comparisons of marginal means (%s adjustment)", adj_label),
    columns = list(list(key = "factor", label = "Factor", type = "string"), 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("factor", "contrast", "estimate", "se", "df", "t", "p_adj", "ci_low", "ci_high")])
}
if (nrow(simple) > 0) {
  tables[[length(tables) + 1]] <- list(key = "simple_effects", title = sprintf("Simple effects of %s within %s", name[["f1"]], name[["f2"]]),
    columns = list(list(key = "effect", label = "Effect", type = "string"), list(key = "f", label = "F", type = "number"),
                   list(key = "df1", label = "df1", type = "number"), list(key = "df2", label = "df2", type = "number"),
                   list(key = "p", label = "p", type = "pvalue")), rows = simple)
  tables[[length(tables) + 1]] <- list(key = "simple_pairs", title = sprintf("Pairwise comparisons of %s within %s", name[["f1"]], name[["f2"]]),
    columns = list(list(key = "within", label = "Within", type = "string"), 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 = simple_pairs)
}
ta <- by_key("f1")
tb <- by_key("f2")
tab_ <- by_key("f1:f2")
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
values$max_interaction_order <- length(safe)
values$n_params <- length(coef(fit))
cs_publish(list(
  method = "anova.factorial",
  methodVersion = "1.0.1",
  title = sprintf("Factorial ANOVA (%s)", paste(factor_cols, collapse = " × ")),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = N,
  summary = sprintf("%s: F = %.2f, %s; %s: F = %.2f, %s; interaction: F = %.2f, %s.", name[["f1"]], ta$f, cs_fmt_p(ta$p), name[["f2"]], tb$f,
                    cs_fmt_p(tb$p), tab_$f, cs_fmt_p(tab_$p)),
  apa = sprintf("interaction: F(%s, %s) = %s, %s", cs_fmt_num(tab_$df, 0), cs_fmt_num(df_resid, 0), cs_fmt_num(tab_$f), cs_fmt_p(tab_$p)),
  statistics = list(list(key = "r2", label = "R²", value = r2), list(key = "df_resid", label = "Residual df", value = df_resid)),
  tables = tables,
  effectSizes = list(
    list(key = "eta_p_a", label = sprintf("Partial η² (%s)", name[["f1"]]), value = ta$eta_p, method = "SS_effect / (SS_effect + SS_residual)"),
    list(key = "eta_p_b", label = sprintf("Partial η² (%s)", name[["f2"]]), value = tb$eta_p, method = "SS_effect / (SS_effect + SS_residual)"),
    list(key = "eta_p_ab", label = sprintf("Partial η² (%s × %s)", name[["f1"]], name[["f2"]]), value = tab_$eta_p, method = "SS_effect / (SS_effect + SS_residual)")
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Model: %s ~ %s with sum-to-zero contrasts; marginal means weight the cells equally.", y, paste(factor_cols, collapse = " * "))),
  values = values,
  charts = list(cs_chart("cell-means", "emm-plot", sprintf("Estimated marginal means of %s", y), list(
    x = cs_col(name[["f1"]], cell_emm$level, "categorical", levels = levels(d$f1)),
    trace = cs_col(name[["f2"]], cell_emm$by, "categorical", levels = levels(d$f2)),
    mean = cs_col(paste("Mean", y), cell_emm$emm, "numeric"),
    low = cs_col("CI low", cell_emm$ci_low, "numeric"),
    high = cs_col("CI high", cell_emm$ci_high, "numeric"))))
))
Python

interaction: F(2, 54) = 4.11, p = .022

R²
0.7937
Residual df
54

Effect size

  • Partial η² (supp) 0.2238
  • Partial η² (dose_f) 0.7731
  • Partial η² (supp × dose_f) 0.1320

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

Assumptions

  • Normality of residuals — Shapiro–Wilk on the residuals: p = .669.
  • Equal variances across cells — Brown–Forsythe F = 1.71, p = .148 across 6 cells.
  • Balanced design — 6 cells with 10 observations each.

ANOVA (Type II sums of squares)

SourceSSdfMSFpη²pω²p
supp205.351205.3515.572< .0010.22380.1954
dose_f2426.4321213.2292.000< .0010.77310.7521
supp × dose_f108.32254.1604.107.0220.13200.0938
Residual712.115413.187————

Estimated marginal means

FactorLevelEMMSECI lowCI high
suppOJ20.6630.663019.33421.993
suppVC16.9630.663015.63418.293
dose_f0.510.6050.81208.97712.233
dose_f119.7350.812018.10721.363
dose_f226.1000.812024.47227.728

Pairwise comparisons of marginal means (Holm adjustment)

FactorContrastDifferenceSEtp adj.CI lowCI high
suppOJ - VC3.7000.93763.946< .0011.8205.580
dose_f0.5 - 1−9.1301.148−7.951< .001−11.432−6.828
dose_f0.5 - 2−15.4951.148−13.493< .001−17.797−13.193
dose_f1 - 2−6.3651.148−5.543< .001−8.667−4.063

Simple effects of supp within dose_f

EffectFdf1df2p
supp | dose_f=0.510.451154.002
supp | dose_f=113.333154< .001
supp | dose_f=20.0024154.961

Pairwise comparisons of supp within dose_f

WithinContrastDifferenceSEtp adj.CI lowCI high
dose_f=0.5OJ - VC5.2501.6243.233.0021.9948.506
dose_f=1OJ - VC5.9301.6243.651< .0012.6749.186
dose_f=2OJ - VC−0.08001.624−0.0493.961−3.3363.176
  • Model: len ~ supp * dose_f with sum-to-zero contrasts; marginal means weight the cells equally.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Factorial ANOVA (two or three between factors)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.factorial 1.0.1 · spec 1dc19eb9e06d66ca
# Dataset: toothgrowth (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/toothgrowth.parquet", columns=["len", "supp", "dose_f"])
n_input = len(df)
df["supp"] = pd.Categorical(df["supp"], categories=["OJ", "VC"])  # stored level order
df["dose_f"] = pd.Categorical(df["dose_f"], categories=["0.5", "1", "2"])  # stored level order
df = df.dropna(subset=["len", "supp", "dose_f"])  # listwise deletion over the analysis columns
df["supp"] = df["supp"].cat.remove_unused_categories()
df["dose_f"] = df["dose_f"].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, ["len", "supp", "dose_f"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
y = "len"
factor_cols = ["supp", "dose_f"]
safe = [f"f{i + 1}" for i in range(len(factor_cols))]  # formula-safe names
name = dict(zip(safe, factor_cols))
d = pd.DataFrame({"y": df[y].to_numpy(dtype=float)})
for s, c in zip(safe, factor_cols):
    d[s] = pd.Categorical(df[c].astype(str), categories=[str(x) for x in df[c].cat.categories])
    if len(d[s].cat.categories) < 2:
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=c, min=2, k=len(d[s].cat.categories))
if d["y"].nunique() < 2:  # a constant outcome leaves nothing to test (the F ratios would be 0/0)
    cs.cs_error("CS_E_CONSTANT", column=y)
cells = d.groupby(safe, observed=False).size()
if (cells == 0).any():
    empty = ["/".join(map(str, ix)) for ix in cells[cells == 0].index][:5]
    raise ValueError(f"Every combination of factor levels needs data; empty cells: {', '.join(empty)}")
if len(d) < len(cells) + 1:  # one value per cell leaves no residual degrees of freedom
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Factorial ANOVA", min=len(cells) + 1, n=len(d))
ss_cells = float(((d["y"] - d.groupby(safe, observed=True)["y"].transform("mean")) ** 2).sum())
if ss_cells <= 1e-12 * float(((d["y"] - d["y"].mean()) ** 2).sum()):  # no variation inside the cells: every F ratio is undefined
    cs.cs_error("CS_E_UNDEFINED", what="Factorial ANOVA", reason=f"{y} does not vary within any cell")
ss_type = "2"
conf = 0.95
alpha = 1 - conf
# Sum-to-zero contrasts (R: contr.sum) so Type III tests are meaningful; Types I/II do not depend on them.
fit = smf.ols("y ~ " + " * ".join(f"C({s}, Sum)" for s in safe), d).fit()
tab, ss_resid, df_resid = csa.anova_table(fit, int(ss_type))
N = len(d)


def term_label(term):
    return " × ".join(name[s] for s in term.split(":"))


terms = []
for _, row in tab.iterrows():
    f, dfe = row["f"], row["df"]
    terms.append({"term": term_label(row["term"]), "key": row["term"], "ss": row["ss"], "df": dfe, "ms": row["ss"] / dfe, "f": f, "p": row["p"],
                  "eta_p": row["ss"] / (row["ss"] + ss_resid), "omega_p": dfe * (f - 1) / (dfe * (f - 1) + N)})
by_key = {t["key"]: t for t in terms}
r2 = float(fit.rsquared)

# %% Estimated marginal means and comparisons
adjust = "holm"
emms, comps = [], []
for s in safe:
    for _, e in emm.emmeans(fit, d, s, safe, [], conf=conf).iterrows():
        emms.append({"factor": name[s], "level": str(e["level"]), "emm": e["emm"], "se": e["se"], "ci_low": e["ci_low"], "ci_high": e["ci_high"]})
    if True:
        for _, c in emm.contrasts(fit, d, s, safe, [], adjust=adjust, conf=conf).iterrows():
            comps.append({"factor": name[s], "contrast": c["contrast"], "estimate": c["estimate"], "se": c["se"], "df": c["df"], "t": c["t"],
                          "p_adj": c["p_adj"], "ci_low": c["ci_low"], "ci_high": c["ci_high"]})
mode = "always"
want_simple = mode == "always" or (mode == "auto" and by_key["f1:f2"]["p"] < alpha)
simple, simple_pairs = [], []
if want_simple:
    for _, j in emm.joint_test(fit, d, "f1", safe, [], by="f2").iterrows():
        simple.append({"effect": f"{name['f1']} | {name['f2']}={j['by']}", "f": j["f"], "df1": j["df1"], "df2": j["df2"], "p": j["p"]})
    for _, c in emm.contrasts(fit, d, "f1", safe, [], by="f2", adjust=adjust, conf=conf).iterrows():
        simple_pairs.append({"within": f"{name['f2']}={c['by']}", "contrast": c["contrast"], "estimate": c["estimate"], "se": c["se"],
                             "t": c["t"], "p_adj": c["p_adj"], "ci_low": c["ci_low"], "ci_high": c["ci_high"]})
cell_emm = emm.emmeans(fit, d, "f1", safe, [], by="f2", conf=conf)

# %% Assumptions
assumptions = []
resid = np.asarray(fit.resid, dtype=float)
sw_p = float(stats.shapiro(resid).pvalue) if 3 <= len(resid) <= 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:
    bad = sw_p < 0.05
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": ("warn" if N < 60 else "info") if bad else "pass", "p": sw_p,
                        "detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)}" + ("; consider a transformation or a robust method." if bad and N < 60 else "; the F tests are robust with this sample size." if bad else ".")})
cell_groups = [g["y"].to_numpy() for _, g in d.groupby(safe, observed=True)]
if min(len(x) for x in cell_groups) >= 2:
    lev = stats.levene(*cell_groups, center="median")  # Brown–Forsythe across cells
    lev_f, lev_p = float(lev.statistic), float(lev.pvalue)
    assumptions.append({"key": "equal_variance", "label": "Equal variances across cells", "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)} across {len(cell_groups)} cells."})
else:  # a cell with a single value: Brown–Forsythe is undefined (R's convention: two values per cell)
    lev_f = lev_p = None
    assumptions.append({"key": "equal_variance", "label": "Equal variances across cells", "status": "info",
                        "detail": "A cell has a single value, so the variances can't be compared across cells."})
sizes = cells.to_numpy()
balanced = sizes.min() == sizes.max()
assumptions.append({"key": "balance", "label": "Balanced design", "status": "pass" if balanced else "info",
                    "detail": f"{len(sizes)} cells with {sizes.min()} observations each." if balanced
                    else f"Cell sizes range from {sizes.min()} to {sizes.max()}; Type {ss_type} sums of squares are used."})

# %% Result
values = {"ss_resid": ss_resid, "df_resid": df_resid, "r2": r2, "n": N, "n_cells": int(len(sizes)), "min_cell": int(sizes.min()),
          "max_cell": int(sizes.max()), "sw_p_resid": sw_p, "levene_f": lev_f, "levene_p": lev_p,
          "factor_a": name["f1"], "factor_b": name["f2"], "ss_type": {"1": "I", "2": "II", "3": "III"}[ss_type]}
for short, key in (("a", "f1"), ("b", "f2"), ("ab", "f1:f2")):
    t = by_key[key]
    values.update({f"f_{short}": t["f"], f"df_{short}": t["df"], f"p_{short}": t["p"], f"eta_p_{short}": t["eta_p"]})
for t in terms:
    for k_ in ("f", "p", "df", "ss", "eta_p", "omega_p"):
        values[f"{k_}[{t['term']}]"] = t[k_]
for e in emms:
    values[f"emm[{e['factor']}: {e['level']}]"] = e["emm"]
for c in comps:
    values[f"diff[{c['factor']}: {c['contrast']}]"] = c["estimate"]
    values[f"p_adj[{c['factor']}: {c['contrast']}]"] = c["p_adj"]
for sres in simple:
    values[f"simple_f[{sres['effect']}]"] = sres["f"]
    values[f"simple_p[{sres['effect']}]"] = sres["p"]
anova_rows = [{k_: t[k_] for k_ in ("term", "ss", "df", "ms", "f", "p", "eta_p", "omega_p")} for t in terms]
anova_rows.append({"term": "Residual", "ss": ss_resid, "df": df_resid, "ms": ss_resid / df_resid})
adj_label = {"tukey": "Tukey", "holm": "Holm", "bonferroni": "Bonferroni", "sidak": "Šidák", "scheffe": "Scheffé", "none": "no"}[adjust]
tables = [
    {"key": "anova", "title": f"ANOVA (Type {values['ss_type']} 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"}, {"key": "omega_p", "label": "ω²p", "type": "number"}], "rows": anova_rows},
    {"key": "emm", "title": "Estimated marginal means", "columns": [
        {"key": "factor", "label": "Factor", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
        {"key": "emm", "label": "EMM", "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": emms},
]
if comps:
    tables.append({"key": "posthoc", "title": f"Pairwise comparisons of marginal means ({adj_label} adjustment)", "columns": [
        {"key": "factor", "label": "Factor", "type": "string"}, {"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})
if simple:
    tables.append({"key": "simple_effects", "title": f"Simple effects of {name['f1']} within {name['f2']}", "columns": [
        {"key": "effect", "label": "Effect", "type": "string"}, {"key": "f", "label": "F", "type": "number"},
        {"key": "df1", "label": "df1", "type": "number"}, {"key": "df2", "label": "df2", "type": "number"},
        {"key": "p", "label": "p", "type": "pvalue"}], "rows": simple})
    tables.append({"key": "simple_pairs", "title": f"Pairwise comparisons of {name['f1']} within {name['f2']}", "columns": [
        {"key": "within", "label": "Within", "type": "string"}, {"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": simple_pairs})
ta, tb, tab_ = by_key["f1"], by_key["f2"], by_key["f1:f2"]
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
values["max_interaction_order"] = len(safe)
values["n_params"] = len(fit.params)
cs.publish({
    "method": "anova.factorial",
    "methodVersion": "1.0.1",
    "title": f"Factorial ANOVA ({' × '.join(factor_cols)})",
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": N,
    "summary": f"{name['f1']}: F = {ta['f']:.2f}, {cs.fmt_p(ta['p'])}; {name['f2']}: F = {tb['f']:.2f}, {cs.fmt_p(tb['p'])}; interaction: F = {tab_['f']:.2f}, {cs.fmt_p(tab_['p'])}.",
    "apa": f"interaction: F({cs.fmt_num(tab_['df'], 0)}, {cs.fmt_num(df_resid, 0)}) = {cs.fmt_num(tab_['f'])}, {cs.fmt_p(tab_['p'])}",
    "statistics": [{"key": "r2", "label": "R²", "value": r2}, {"key": "df_resid", "label": "Residual df", "value": df_resid}],
    "tables": tables,
    "effectSizes": [{"key": f"eta_p_{s}", "label": f"Partial η² ({lab})", "value": by_key[k_]["eta_p"], "method": "SS_effect / (SS_effect + SS_residual)"}
                    for s, k_, lab in (("a", "f1", name["f1"]), ("b", "f2", name["f2"]), ("ab", "f1:f2", f"{name['f1']} × {name['f2']}"))],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Model: {y} ~ {' * '.join(factor_cols)} with sum-to-zero contrasts; marginal means weight the cells equally."],
    "values": values,
    "charts": [cs.chart("cell-means", "emm-plot", f"Estimated marginal means of {y}", {
        "x": cs.col(name["f1"], [str(v) for v in cell_emm["level"]], "categorical", levels=[str(x) for x in d["f1"].cat.categories]),
        "trace": cs.col(name["f2"], [str(v) for v in cell_emm["by"]], "categorical", levels=[str(x) for x in d["f2"].cat.categories]),
        "mean": cs.col(f"Mean {y}", cell_emm["emm"].to_numpy(), "numeric"),
        "low": cs.col("CI low", cell_emm["ci_low"].to_numpy(), "numeric"),
        "high": cs.col("CI high", cell_emm["ci_high"].to_numpy(), "numeric")})],
})

The interaction is F(2, 54) = 4.11, p = .022, partial η2\eta^2 = 0.13.

So "OJ is better than VC" is too simple a sentence. The advantage of OJ at low doses shrinks as the dose rises. Report simple effects, the effect of supplement at each dose.

05

Unbalanced data

Read

In a balanced design like ToothGrowth, the factors are uncorrelated, so sums of squares don't depend on order. In an unbalanced one, such as mtcars with cell sizes from 2 to 12, they do:

TypeType I, II and III sums of squaresWays to split variance among correlated factors in unbalanced ANOVA; they answer different questions.Each term is adjusted forUse when
ITerms before it, in orderYou have a defensible order
IIAll other main effectsThe interaction is absent
IIIEverything elseEffects are averaged equally over cells

Packages default to different types, so CodeSplash always states its choice.

06

Check your understanding

Checkpoint

Check yourself

A study crosses 3 diets with 4 exercise plans. How many cells does the design have?

Show the answer

Answer: 12

3 × 4 = 12 cells, one for each combination.

Check yourself

Put these steps in the order you should read a two-way ANOVA.

  1. 1Look at the interaction
  2. 2If it doesn't, interpret the main effects
  3. 3If it matters, examine simple effects

Show the answer

The order:

  1. Look at the interaction
  2. If it matters, examine simple effects
  3. If it doesn't, interpret the main effects

The interaction decides whether a main effect is a fair summary.

Check yourself

Drug A beats placebo by 10 points in women and by −10 points in men, with equal numbers of each. What will the table show?

Show the answer

Answer: b

The effects cancel when averaged over sex, so the main effect is close to zero. The interaction catches the reversal.

07

Do it in CodeSplash

In the app

Pick an Outcome and two or three Factors. Choose Sums of squares, and set Simple effects of the first factor to always when you want them regardless of p. The card includes estimated marginal means.

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

df = pd.read_csv("toothgrowth.csv")
fit = smf.ols("len ~ C(supp) * C(dose)", data=df).fit()
print(sm.stats.anova_lm(fit, typ=2))
R
# install.packages("car")
df <- transform(ToothGrowth, dose = factor(dose))
fit <- lm(len ~ supp * dose, data = df)
car::Anova(fit, type = 2)
08

Recap

Recap
  • A factorial design tests main effects and whether effects depend on each other.
  • Read the interaction first. If it matters, report simple effects.
  • Sums-of-squares type matters only when the design is unbalanced, and you should say which you used.

Concepts in this lesson