Many tests and the family-wise error rate
Run enough tests and something will look significant. Learn what family-wise control promises, how Bonferroni, Holm and Tukey deliver it, and how to choose among post hoc procedures.
What runs in CodeSplash
- STAT041Tukey HSD and Tukey–Kramer Runs in CodeSplash
- STAT042Dunnett test Runs in CodeSplash
- STAT043Scheffé test Runs in CodeSplash
- STAT044Fisher protected least significant difference Runs in CodeSplash
- STAT045Games–Howell test Runs in CodeSplash
- STAT046Tamhane T2 test Runs in CodeSplash
- STAT047Dunnett T3 test Runs in CodeSplash
- STAT048Ury–Wiggins–Hochberg test Runs in CodeSplash
- STAT049Dunn test Runs in CodeSplash
- STAT050Conover–Iman test Runs in CodeSplash
- STAT051Nemenyi test Runs in CodeSplash
- STAT052Dwass–Steel–Critchlow–Fligner or Steel–Dwass family Runs in CodeSplash
- STAT053Steel many to one rank test Runs in CodeSplash
- Pairwise comparisons (Tukey, Games–Howell, Dunnett, Dunn, Steel–Dwass …) Verified in Python and R
- One-way ANOVA (Welch / classic) Verified in Python and R
- Kruskal–Wallis test Verified in Python and R
You will be able to
- Compute how the chance of a false alarm grows with the number of tests
- Apply Bonferroni and Holm to a list of p-values
- Choose a post hoc procedure from the design and the variances
- Use a test family in the Multiple testing page
Read first
Twenty chances to be wrong
PredictPredict first
You run 20 independent tests at , and every null hypothesis is true. How likely is at least one "significant" result?
Make your guess between 0 and 1 chance of at least one, then reveal.
Reveal
. Each test keeps its promise, and the set of tests doesn't. That chance is the family-wise error rateFamily-wise error rateThe chance of at least one false positive across a family of tests.: the probability of one or more false positives among a family of tests.
Watch it grow
ExploreChange the number of tests, then add a few real effects. Compare the error rate with no correction against Bonferroni, and look at how many real effects each one finds.
BExplorable · The family-wise error rate
If you run many tests, how likely is at least one false alarm, and what does correcting cost?
Without correction, how often does this family produce at least one false alarm?
Commit your prediction above to see the result
Make your prediction to see the result.
Correction isn't free. Every reduction in false alarms comes out of power, so a family should hold only the tests that answer one question.
Bonferroni and Holm
ReadBonferroniBonferroni correctionMultiply each p-value by the number of tests (or divide α by it); simple and conservative. tests each of hypotheses at . It is simple and valid under any dependence, but conservative.
HolmHolm correctionA step-down version of Bonferroni that controls the same error rate with more power; use it instead. is always at least as powerful, so use it instead. Sort the p-values from smallest up, and compare:
Stop at the first failure. Everything before it is significant. Holm spends less on each later comparison because earlier rejections have already paid part of the bill.
A worked Holm
CheckpointFour p-values, α = .05
The sorted p-values are , , and .
- Compare with . It passes.
- Compare with . It passes.
Try this step yourself, then reveal it
Compare with . It fails, so stop.Try this step yourself, then reveal it
Holm rejects two hypotheses. Bonferroni's single cutoff of rejects only the first.
Check yourself
Holm at with p-values .001, .015, .040, .300. How many hypotheses are rejected?
Show the answer
Answer: 2
.001 ≤ .0125 passes; .015 ≤ .0167 passes; .040 > .025 fails, so stop. Two rejections.
Pairwise comparisons have their own family
ReadAfter a significant ANOVA, you usually compare every pair: groups give comparisons. On chickwts that is 6 feeds and 15 pairs.
Tukey's HSDTukey HSDCompares all pairs of group means with family-wise control, assuming equal variances. uses the studentized range, built for this exact family. It found 8 pairs that differ, and its multiplier for each interval is 2.94.
Tukey–Kramer: smallest adjusted p < .001
- Significant comparisons
- 8
- Smallest adjusted p
- < .001
Plots
View data
| Difference in weight | CI high | Contrast | CI low |
|---|---|---|---|
| 163.38 | 232.35 | casein - horsebean | 94.420 |
| 104.83 | 170.59 | casein - linseed | 39.079 |
| 46.674 | 113.91 | casein - meatmeal | −20.558 |
| 77.155 | 140.52 | casein - soybean | 13.792 |
| −5.333 | 60.421 | casein - sunflower | −71.087 |
| −58.550 | 10.414 | horsebean - linseed | −127.51 |
| −116.71 | −46.335 | horsebean - meatmeal | −187.08 |
| −86.229 | −19.542 | horsebean - soybean | −152.92 |
| −168.72 | −99.753 | horsebean - sunflower | −237.68 |
| −58.159 | 9.073 | linseed - meatmeal | −125.39 |
| −27.679 | 35.684 | linseed - soybean | −91.041 |
| −110.17 | −44.413 | linseed - sunflower | −175.92 |
| 30.481 | 95.375 | meatmeal - soybean | −34.414 |
| −52.008 | 15.224 | meatmeal - sunflower | −119.24 |
| −82.488 | −19.126 | soybean - sunflower | −145.85 |
View data
| Mean weight | CI high | feed | Letters | CI low |
|---|---|---|---|---|
| 323.58 | 364.52 | casein | a | 282.64 |
| 160.20 | 187.83 | horsebean | b | 132.57 |
| 218.75 | 251.94 | linseed | bc | 185.56 |
| 276.91 | 320.51 | meatmeal | ac | 233.31 |
| 246.43 | 277.68 | soybean | c | 215.18 |
| 328.92 | 359.95 | sunflower | a | 297.89 |
Assumptions
- Equal variances — Brown–Forsythe F = 0.75, p = .590.
- Normality within groups — Shapiro–Wilk on the within-group residuals: p = .627.
Tukey–Kramer comparisons
| Contrast | Difference | SE | q | p (unadjusted) | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| casein - horsebean | 163.38 | 16.607 | 9.838 | < .001 | < .001 | 94.420 | 232.35 |
| casein - linseed | 104.83 | 15.834 | 6.621 | < .001 | < .001 | 39.079 | 170.59 |
| casein - meatmeal | 46.674 | 16.190 | 2.883 | .046 | .332 | −20.558 | 113.91 |
| casein - soybean | 77.155 | 15.258 | 5.057 | < .001 | .008 | 13.792 | 140.52 |
| casein - sunflower | −5.333 | 15.834 | −0.3368 | .812 | 1.000 | −71.087 | 60.421 |
| horsebean - linseed | −58.550 | 16.607 | −3.526 | .015 | .141 | −127.51 | 10.414 |
| horsebean - meatmeal | −116.71 | 16.946 | −6.887 | < .001 | < .001 | −187.08 | −46.335 |
| horsebean - soybean | −86.229 | 16.059 | −5.370 | < .001 | .004 | −152.92 | −19.542 |
| horsebean - sunflower | −168.72 | 16.607 | −10.160 | < .001 | < .001 | −237.68 | −99.753 |
| linseed - meatmeal | −58.159 | 16.190 | −3.592 | .013 | .128 | −125.39 | 9.073 |
| linseed - soybean | −27.679 | 15.258 | −1.814 | .204 | .793 | −91.041 | 35.684 |
| linseed - sunflower | −110.17 | 15.834 | −6.958 | < .001 | < .001 | −175.92 | −44.413 |
| meatmeal - soybean | 30.481 | 15.627 | 1.951 | .173 | .739 | −34.414 | 95.375 |
| meatmeal - sunflower | −52.008 | 16.190 | −3.212 | .026 | .221 | −119.24 | 15.224 |
| soybean - sunflower | −82.488 | 15.258 | −5.406 | < .001 | .004 | −145.85 | −19.126 |
Group means and letters (groups sharing a letter do not differ)
| feed | n | Mean | SD | Letters |
|---|---|---|---|---|
| casein | 12 | 323.58 | 64.434 | a |
| horsebean | 10 | 160.20 | 38.626 | b |
| linseed | 12 | 218.75 | 52.236 | bc |
| meatmeal | 11 | 276.91 | 64.901 | ac |
| soybean | 14 | 246.43 | 54.129 | c |
| sunflower | 12 | 328.92 | 48.836 | a |
- Contrasts are first − second level; α = 0.05.
The exact R script · R R version 4.5.1 (2025-06-13)
# Pairwise comparisons (Tukey, Games–Howell, Dunnett, Dunn, Steel–Dwass …)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method posthoc.pairwise 1.1.3 · spec 2f89f3aaf579c117
# Dataset: chickwts (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/chickwts.parquet", col_select = c("weight", "feed")))
n_input <- nrow(df)
df[["feed"]] <- factor(df[["feed"]], levels = c("casein", "horsebean", "linseed", "meatmeal", "soybean", "sunflower")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "feed")]), , 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("weight", "feed")) # infinite values stop the run (registry/errors.yaml)
# %% Comparisons
y <- "weight"
g <- "feed"
levels_g <- levels(df[[g]])
groups <- lapply(levels_g, function(lv) df[[y]][df[[g]] == lv])
k <- length(levels_g)
N <- sum(lengths(groups))
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (length(unique(df[[y]])) < 2) cs_error("CS_E_CONSTANT", column = y) # a constant outcome: every difference and its standard error are zero
method <- "tukey"
conf <- 0.95
alpha <- 1 - conf
adjust <- "holm"
pooled <- FALSE
RANK <- c("dunn", "conover_iman", "nemenyi", "dscf", "steel") # compare ranks, not means
MANY_TO_ONE <- c("dunnett", "steel") # each group vs a control
ss_groups <- sum(vapply(groups, function(x) sum((x - mean(x))^2), 0))
if (!(method %in% RANK) && ss_groups <= 1e-12 * sum((df[[y]] - mean(df[[y]]))^2)) {
# no variation inside the groups: every standard error is zero, so comparisons of means are undefined
cs_error("CS_E_UNDEFINED", what = "The comparison of means", reason = sprintf("%s does not vary within any group", y))
}
alternative <- "two-sided"
uwh_step <- "bonferroni"
critical <- NULL
omnibus_f <- NULL
omnibus_p <- NULL
if (method == "tukey") {
rows <- cs_tukey_kramer(groups, levels_g, conf)
critical <- qtukey(conf, k, N - k) / sqrt(2)
} else if (method == "scheffe") {
sc <- cs_scheffe(groups, levels_g, conf)
rows <- sc$rows
critical <- sc$crit
} else if (method == "lsd") {
ls <- cs_lsd(groups, levels_g, conf) # gated by the one-way ANOVA F
rows <- ls$rows
omnibus_f <- ls$f
omnibus_p <- ls$p
critical <- ls$crit
} else if (method == "games_howell") {
rows <- cs_games_howell(groups, levels_g, conf)
} else if (method == "tamhane_t2") {
rows <- cs_tamhane_t2(groups, levels_g, conf)
} else if (method == "dunnett_t3") {
rows <- cs_dunnett_t3(groups, levels_g, conf)
} else if (method == "uwh") {
rows <- cs_ury_wiggins_hochberg(groups, levels_g, step = uwh_step, conf = conf)
} else if (method %in% MANY_TO_ONE) {
reference <- levels_g[1] # control group
if (!(reference %in% levels_g)) stop(sprintf("The control group '%s' has no data", reference))
dn <- if (method == "dunnett") cs_dunnett(groups, levels_g, match(reference, levels_g), conf) else
cs_steel(groups, levels_g, match(reference, levels_g), sub("-", "_", alternative, fixed = TRUE), conf)
rows <- dn$rows
critical <- dn$crit
} else if (method == "pairwise_t") {
rows <- cs_pairwise_t(groups, levels_g, pooled = pooled, adjust = adjust, conf = conf)
} else if (method == "conover_iman") {
rows <- cs_conover_iman(groups, levels_g, adjust = adjust)$rows
} else if (method == "nemenyi") {
rows <- cs_nemenyi(groups, levels_g)
} else if (method == "dscf") {
rows <- cs_dscf(groups, levels_g)
} else {
rows <- cs_dunn(groups, levels_g, adjust = adjust)
}
sig_rows <- which(rows$p_adj < alpha)
letters_ <- if (!(method %in% MANY_TO_ONE)) cs_cld(levels_g, lapply(sig_rows, function(x) c(rows$i[x], rows$j[x]))) else character(0)
labels <- c(tukey = "Tukey–Kramer", scheffe = "Scheffé", lsd = "Fisher's protected LSD", games_howell = "Games–Howell",
tamhane_t2 = "Tamhane T2", dunnett_t3 = "Dunnett T3",
uwh = if (uwh_step == "bonferroni") "Ury–Wiggins" else "Welch t (Hochberg step-up)", dunnett = "Dunnett", dunn = "Dunn",
conover_iman = "Conover–Iman", nemenyi = "Nemenyi", dscf = "Dwass–Steel–Critchlow–Fligner",
steel = paste0("Steel", if (alternative == "two-sided") "" else sprintf(" (one-sided, %s)", alternative)),
pairwise_t = paste(if (pooled) "Pooled-SD" else "Welch", "t"))
method_label <- labels[[method]]
if (method %in% c("pairwise_t", "dunn", "conover_iman") && adjust != "none") {
method_label <- paste0(method_label, c(holm = " (Holm)", bonferroni = " (Bonferroni)", hochberg = " (Hochberg)", hommel = " (Hommel)",
BH = " (Benjamini–Hochberg)", BY = " (Benjamini–Yekutieli)", sidak = " (Šidák)",
`holm-sidak` = " (Holm–Šidák)")[[adjust]])
}
# %% Assumptions
assumptions <- list()
z <- abs(df[[y]] - ave(df[[y]], df[[g]], FUN = median))
pooled_method <- method %in% c("tukey", "scheffe", "lsd", "dunnett") || (method == "pairwise_t" && pooled)
if (min(lengths(groups)) >= 2 && !all(vapply(groups, function(x) length(unique(x)) == 1, TRUE))) {
lev <- oneway.test(z ~ df[[g]], var.equal = TRUE) # Brown-Forsythe
lev_f <- unname(lev$statistic)
lev_p <- lev$p.value
assumptions[[1]] <- list(key = "equal_variance", label = "Equal variances", statistic = lev_f, p = lev_p,
status = if (pooled_method) (if (lev_p < 0.05) "warn" else "pass") else "info",
detail = paste0(sprintf("Brown–Forsythe F = %.2f, %s", lev_f, cs_fmt_p(lev_p)),
if (pooled_method) "." else "; this method does not pool the variances."))
} else { # a group with a single value, or no group varies: Brown-Forsythe is undefined (as oneway.test)
assumptions[[1]] <- list(key = "equal_variance", label = "Equal variances", status = "info",
detail = "The variances can't be compared: a group has a single value, or no group varies.")
}
resid <- unlist(lapply(groups, function(x) x - mean(x)))
# Shapiro-Wilk needs 3 to 5000 values that are not all the same (shapiro.test stops otherwise).
sw_p <- if (length(resid) >= 3 && length(resid) <= 5000 && diff(range(resid)) > 0) shapiro.test(resid)$p.value else NULL
if (method %in% RANK || is.null(sw_p)) {
assumptions[[2]] <- list(key = "normality", label = "Normality within groups", status = "info",
detail = if (method %in% RANK) sprintf("%s compares ranks and does not assume normality.", method_label) else "Too few (or too many) values for Shapiro–Wilk.")
} else {
assumptions[[2]] <- list(key = "normality", label = "Normality within groups", status = if (sw_p >= 0.05) "pass" else if (N < 60) "warn" else "info",
p = sw_p, detail = sprintf("Shapiro–Wilk on the within-group residuals: %s.", cs_fmt_p(sw_p)))
}
if (method == "lsd") {
gate <- omnibus_p < alpha
assumptions[[3]] <- list(key = "omnibus", label = "Omnibus test rejects", statistic = omnibus_f, p = omnibus_p,
status = if (gate) "pass" else "warn",
detail = paste0(sprintf("One-way ANOVA F = %.2f, %s; ", omnibus_f, cs_fmt_p(omnibus_p)),
if (gate) "the pairwise comparisons are protected." else "the ANOVA does not reject, so protected LSD declares no pairwise difference (every adjusted p is 1)."))
}
# %% Result
contrasts <- paste(rows$a, "-", rows$b)
values <- list(k = k, n = N, n_comparisons = nrow(rows), n_significant = length(sig_rows), p_min = min(rows$p_adj),
method_label = method_label, critical_value = critical, omnibus_f = omnibus_f, omnibus_p = omnibus_p)
for (i in seq_len(nrow(rows))) {
values[[sprintf("diff[%s]", contrasts[i])]] <- rows$estimate[i]
values[[sprintf("p_adj[%s]", contrasts[i])]] <- rows$p_adj[i]
if (!(method %in% RANK)) {
values[[sprintf("ci_low[%s]", contrasts[i])]] <- rows$ci_low[i]
values[[sprintf("ci_high[%s]", contrasts[i])]] <- rows$ci_high[i]
}
}
for (lv in names(letters_)) values[[sprintf("letters[%s]", lv)]] <- letters_[[lv]]
est_label <- if (method %in% c("dscf", "steel")) "Location shift (Hodges–Lehmann)" else if (method %in% RANK) "Mean-rank difference" else "Difference"
stat_label <- c(tukey = "q", scheffe = "F", lsd = "t", games_howell = "q", tamhane_t2 = "t", dunnett_t3 = "t", uwh = "t",
dunnett = "t", pairwise_t = "t", dunn = "z", conover_iman = "t", nemenyi = "q", dscf = "q", steel = "z")[[method]]
columns <- list(list(key = "contrast", label = "Contrast", type = "string"), list(key = "estimate", label = est_label, type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "stat", label = stat_label, type = "number"),
list(key = "p", label = "p (unadjusted)", type = "pvalue"), list(key = "p_adj", label = "p adj.", type = "pvalue"))
if (!(method %in% RANK)) columns <- c(columns, list(list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number")))
table_rows <- data.frame(contrast = contrasts, rows[, c("estimate", "se", "stat", "p", "p_adj", "ci_low", "ci_high")], stringsAsFactors = FALSE)
descr <- data.frame(group = levels_g, n = lengths(groups), mean = vapply(groups, mean, 0),
sd = vapply(groups, function(x) if (length(x) > 1) sd(x) else NA_real_, 0), stringsAsFactors = FALSE)
desc_cols <- list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"))
if (length(letters_)) {
descr$letters <- unname(letters_[levels_g])
desc_cols <- c(desc_cols, list(list(key = "letters", label = "Letters", type = "string")))
}
tables <- list(list(key = "posthoc", title = sprintf("%s comparisons", method_label), columns = columns, rows = table_rows),
list(key = "descriptives", title = paste0("Group means", if (length(letters_)) " and letters (groups sharing a letter do not differ)" else ""),
columns = desc_cols, rows = descr))
if (method %in% RANK) {
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
chart <- cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g)))
} else {
simult <- if (method %in% c("tukey", "scheffe", "games_howell", "tamhane_t2", "dunnett_t3", "uwh", "dunnett")) "simultaneous " else ""
chart <- cs_chart("differences", "forest", sprintf("Differences in mean %s (%s %sCI)", y, sprintf("%.0f%%", conf * 100), simult), list(
label = cs_col("Contrast", contrasts, "categorical"),
estimate = cs_col(sprintf("Difference in %s", y), rows$estimate, "numeric"),
low = cs_col("CI low", rows$ci_low, "numeric"),
high = cs_col("CI high", rows$ci_high, "numeric")), controls = list(reference = 0))
}
charts <- list(chart)
if (length(letters_) && k >= 3) {
if (method %in% RANK) {
# Mean ranks from the joint ranking; groups that share a letter are joined by a bar (Demsar-style).
ranks_all <- rank(unlist(groups))
cuts <- cumsum(c(0, lengths(groups)))
charts[[2]] <- cs_chart("cld", "critical-difference", sprintf("Mean ranks of %s: groups joined by a bar do not differ", y), list(
label = cs_col(g, levels_g, "categorical"),
rank = cs_col("Mean rank", vapply(seq_len(k), function(i) mean(ranks_all[(cuts[i] + 1):cuts[i + 1]]), numeric(1)), "numeric"),
letters = cs_col("Letters", unname(letters_[levels_g]), "categorical")))
} else {
half <- vapply(groups, function(x) if (length(x) > 1) qt(0.5 + conf / 2, length(x) - 1) * sd(x) / sqrt(length(x)) else NaN, numeric(1))
mns <- vapply(groups, mean, numeric(1))
charts[[2]] <- cs_chart("cld", "cld-plot", sprintf("Mean %s by %s (%s CI): groups sharing a letter do not differ", y, g, sprintf("%.0f%%", conf * 100)), list(
label = cs_col(g, levels_g, "categorical"),
center = cs_col(sprintf("Mean %s", y), mns, "numeric"),
low = cs_col("CI low", mns - half, "numeric"),
high = cs_col("CI high", mns + half, "numeric"),
letters = cs_col("Letters", unname(letters_[levels_g]), "categorical")))
}
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
cs_publish(list(
method = "posthoc.pairwise",
methodVersion = "1.1.3",
title = sprintf("Pairwise comparisons: %s", method_label),
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = sprintf("%d of %d %s comparisons are significant at α = %s (smallest adjusted %s).", length(sig_rows), nrow(rows), method_label,
format(alpha), cs_fmt_p(min(rows$p_adj))),
apa = sprintf("%s: smallest adjusted %s", method_label, cs_fmt_p(min(rows$p_adj))),
statistics = list(list(key = "n_significant", label = "Significant comparisons", value = length(sig_rows), format = "integer"),
list(key = "p_min", label = "Smallest adjusted p", value = min(rows$p_adj), format = "p")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Contrasts are first − second level%s; α = %s.", if (method %in% MANY_TO_ONE) sprintf(" (each group − %s)", rows$b[1]) else "", format(alpha))),
values = values,
charts = charts
))
Tukey–Kramer: smallest adjusted p < .001
- Significant comparisons
- 8
- Smallest adjusted p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Equal variances — Brown–Forsythe F = 0.75, p = .590.
- Normality within groups — Shapiro–Wilk on the within-group residuals: p = .627.
Tukey–Kramer comparisons
| Contrast | Difference | SE | q | p (unadjusted) | p adj. | CI low | CI high |
|---|---|---|---|---|---|---|---|
| casein - horsebean | 163.38 | 16.607 | 9.838 | < .001 | < .001 | 94.420 | 232.35 |
| casein - linseed | 104.83 | 15.834 | 6.621 | < .001 | < .001 | 39.079 | 170.59 |
| casein - meatmeal | 46.674 | 16.190 | 2.883 | .046 | .332 | −20.558 | 113.91 |
| casein - soybean | 77.155 | 15.258 | 5.057 | < .001 | .008 | 13.792 | 140.52 |
| casein - sunflower | −5.333 | 15.834 | −0.3368 | .812 | 1.000 | −71.087 | 60.421 |
| horsebean - linseed | −58.550 | 16.607 | −3.526 | .015 | .141 | −127.51 | 10.414 |
| horsebean - meatmeal | −116.71 | 16.946 | −6.887 | < .001 | < .001 | −187.08 | −46.335 |
| horsebean - soybean | −86.229 | 16.059 | −5.370 | < .001 | .004 | −152.92 | −19.542 |
| horsebean - sunflower | −168.72 | 16.607 | −10.160 | < .001 | < .001 | −237.68 | −99.753 |
| linseed - meatmeal | −58.159 | 16.190 | −3.592 | .013 | .128 | −125.39 | 9.073 |
| linseed - soybean | −27.679 | 15.258 | −1.814 | .204 | .793 | −91.041 | 35.684 |
| linseed - sunflower | −110.17 | 15.834 | −6.958 | < .001 | < .001 | −175.92 | −44.413 |
| meatmeal - soybean | 30.481 | 15.627 | 1.951 | .173 | .739 | −34.414 | 95.375 |
| meatmeal - sunflower | −52.008 | 16.190 | −3.212 | .026 | .221 | −119.24 | 15.224 |
| soybean - sunflower | −82.488 | 15.258 | −5.406 | < .001 | .004 | −145.85 | −19.126 |
Group means and letters (groups sharing a letter do not differ)
| feed | n | Mean | SD | Letters |
|---|---|---|---|---|
| casein | 12 | 323.58 | 64.434 | a |
| horsebean | 10 | 160.20 | 38.626 | b |
| linseed | 12 | 218.75 | 52.236 | bc |
| meatmeal | 11 | 276.91 | 64.901 | ac |
| soybean | 14 | 246.43 | 54.129 | c |
| sunflower | 12 | 328.92 | 48.836 | a |
- Contrasts are first − second level; α = 0.05.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Pairwise comparisons (Tukey, Games–Howell, Dunnett, Dunn, Steel–Dwass …)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method posthoc.pairwise 1.1.3 · spec 2f89f3aaf579c117
# Dataset: chickwts (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
from scipy import stats
import codesplash as cs
from codesplash.stats import posthoc as ph
# %% Data
df = pd.read_parquet("tests/parity/fixtures/chickwts.parquet", columns=["weight", "feed"])
n_input = len(df)
df["feed"] = pd.Categorical(df["feed"], categories=["casein", "horsebean", "linseed", "meatmeal", "soybean", "sunflower"]) # stored level order
df = df.dropna(subset=["weight", "feed"]) # listwise deletion over the analysis columns
df["feed"] = df["feed"].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, ["weight", "feed"]) # infinite values stop the run (registry/errors.yaml)
# %% Comparisons
y, g = "weight", "feed"
levels = [str(x) for x in df[g].cat.categories]
groups = [df.loc[df[g] == lv, y].to_numpy(dtype=float) for lv in df[g].cat.categories]
k, N = len(levels), int(sum(len(x) for x in groups))
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
if df[y].nunique() < 2: # a constant outcome: every difference and its standard error are zero
cs.cs_error("CS_E_CONSTANT", column=y)
method = "tukey"
conf = 0.95
alpha = 1 - conf
adjust = "holm"
RANK = ("dunn", "conover_iman", "nemenyi", "dscf", "steel") # compare ranks, not means
MANY_TO_ONE = ("dunnett", "steel") # each group vs a control
ss_groups = float(sum(((x - x.mean()) ** 2).sum() for x in groups))
if method not in RANK and ss_groups <= 1e-12 * float(((df[y] - df[y].mean()) ** 2).sum()):
# no variation inside the groups: every standard error is zero, so comparisons of means are undefined
cs.cs_error("CS_E_UNDEFINED", what="The comparison of means", reason=f"{y} does not vary within any group")
alternative = "two-sided"
uwh_step = "bonferroni"
critical = None
omnibus_f = omnibus_p = None
if method == "tukey":
rows = ph.tukey_kramer(groups, levels, conf)
# R's qtukey needs two or more residual degrees of freedom and returns NaN below; both engines do.
critical = float(stats.studentized_range.ppf(conf, k, N - k) / np.sqrt(2)) if N - k >= 2 else float("nan")
elif method == "scheffe":
rows, critical = ph.scheffe(groups, levels, conf)
elif method == "lsd":
rows, omnibus_f, omnibus_p, critical = ph.lsd(groups, levels, conf) # gated by the one-way ANOVA F
elif method == "games_howell":
rows = ph.games_howell(groups, levels, conf)
elif method == "tamhane_t2":
rows = ph.tamhane_t2(groups, levels, conf)
elif method == "dunnett_t3":
rows = ph.dunnett_t3(groups, levels, conf)
elif method == "uwh":
rows = ph.ury_wiggins_hochberg(groups, levels, step=uwh_step, conf=conf)
elif method in MANY_TO_ONE:
reference = levels[0] # control group
if reference not in levels:
raise ValueError(f"The control group {reference!r} has no data")
if method == "dunnett":
rows, critical = ph.dunnett(groups, levels, levels.index(reference), conf)
else:
rows, critical = ph.steel(groups, levels, levels.index(reference), alternative.replace("-", "_"), conf)
elif method == "pairwise_t":
rows = ph.pairwise_t(groups, levels, pooled=False, adjust=adjust, conf=conf)
elif method == "conover_iman":
rows, _kw_h = ph.conover_iman(groups, levels, adjust=adjust)
elif method == "nemenyi":
rows = ph.nemenyi(groups, levels)
elif method == "dscf":
rows = ph.dscf(groups, levels)
else:
rows = ph.dunn(groups, levels, adjust=adjust)
signif = [(r["i"], r["j"]) for r in rows if r["p_adj"] < alpha]
letters = ph.cld(levels, signif) if method not in MANY_TO_ONE else {}
labels = {"tukey": "Tukey–Kramer", "scheffe": "Scheffé", "lsd": "Fisher's protected LSD", "games_howell": "Games–Howell",
"tamhane_t2": "Tamhane T2", "dunnett_t3": "Dunnett T3",
"uwh": "Ury–Wiggins" if uwh_step == "bonferroni" else "Welch t (Hochberg step-up)", "dunnett": "Dunnett", "dunn": "Dunn",
"conover_iman": "Conover–Iman", "nemenyi": "Nemenyi", "dscf": "Dwass–Steel–Critchlow–Fligner",
"steel": "Steel" + ("" if alternative == "two-sided" else f" (one-sided, {alternative})"),
"pairwise_t": ("Pooled-SD" if False else "Welch") + " t"}
method_label = labels[method]
if method in ("pairwise_t", "dunn", "conover_iman") and adjust != "none":
method_label += {"holm": " (Holm)", "bonferroni": " (Bonferroni)", "hochberg": " (Hochberg)", "hommel": " (Hommel)", "BH": " (Benjamini–Hochberg)",
"BY": " (Benjamini–Yekutieli)", "sidak": " (Šidák)", "holm-sidak": " (Holm–Šidák)"}[adjust]
# %% Assumptions
assumptions = []
pooled_method = method in ("tukey", "scheffe", "lsd", "dunnett") or (method == "pairwise_t" and False)
if min(len(x) for x in groups) >= 2 and not all(len(np.unique(x)) == 1 for x in groups):
lev = stats.levene(*groups, center="median") # Brown–Forsythe
assumptions.append({"key": "equal_variance", "label": "Equal variances", "statistic": float(lev.statistic), "p": float(lev.pvalue),
"status": ("warn" if lev.pvalue < 0.05 else "pass") if pooled_method else "info",
"detail": f"Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)}"
+ ("." if pooled_method else "; this method does not pool the variances.")})
else: # a group with a single value, or no group varies: Brown–Forsythe is undefined (as R's oneway.test)
assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": "info",
"detail": "The variances can't be compared: a group has a single value, or no group varies."})
resid = np.concatenate([x - x.mean() for x in groups])
# Shapiro–Wilk needs 3 to 5000 values that are not all the same (as R's shapiro.test).
sw_p = float(stats.shapiro(resid).pvalue) if 3 <= len(resid) <= 5000 and np.ptp(resid) > 0 else None
if method in RANK or sw_p is None:
assumptions.append({"key": "normality", "label": "Normality within groups", "status": "info",
"detail": f"{method_label} compares ranks and does not assume normality." if method in RANK else "Too few (or too many) values for Shapiro–Wilk."})
else:
assumptions.append({"key": "normality", "label": "Normality within groups", "status": "pass" if sw_p >= 0.05 else ("warn" if N < 60 else "info"), "p": sw_p,
"detail": f"Shapiro–Wilk on the within-group residuals: {cs.fmt_p(sw_p)}."})
if method == "lsd":
gate = omnibus_p < alpha
assumptions.append({"key": "omnibus", "label": "Omnibus test rejects", "statistic": omnibus_f, "p": omnibus_p,
"status": "pass" if gate else "warn",
"detail": f"One-way ANOVA F = {omnibus_f:.2f}, {cs.fmt_p(omnibus_p)}; "
+ ("the pairwise comparisons are protected." if gate else "the ANOVA does not reject, so protected LSD declares no pairwise difference (every adjusted p is 1).")})
# %% Result
p_adj = [r["p_adj"] for r in rows]
values = {"k": k, "n": N, "n_comparisons": len(rows), "n_significant": len(signif), "p_min": float(min(p_adj)),
"method_label": method_label, "critical_value": critical, "omnibus_f": omnibus_f, "omnibus_p": omnibus_p}
for r in rows:
c = f"{r['a']} - {r['b']}"
values[f"diff[{c}]"] = r["estimate"]
values[f"p_adj[{c}]"] = r["p_adj"]
if method not in RANK:
values[f"ci_low[{c}]"] = r["ci_low"]
values[f"ci_high[{c}]"] = r["ci_high"]
for lv, s in letters.items():
values[f"letters[{lv}]"] = s
est_label = ("Location shift (Hodges–Lehmann)" if method in ("dscf", "steel") else "Mean-rank difference") if method in RANK else "Difference"
stat_label = {"tukey": "q", "scheffe": "F", "lsd": "t", "games_howell": "q", "tamhane_t2": "t", "dunnett_t3": "t", "uwh": "t",
"dunnett": "t", "pairwise_t": "t", "dunn": "z", "conover_iman": "t", "nemenyi": "q", "dscf": "q", "steel": "z"}[method]
columns = [{"key": "contrast", "label": "Contrast", "type": "string"}, {"key": "estimate", "label": est_label, "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "stat", "label": stat_label, "type": "number"},
{"key": "p", "label": "p (unadjusted)", "type": "pvalue"}, {"key": "p_adj", "label": "p adj.", "type": "pvalue"}]
if method not in RANK:
columns += [{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"}]
table_rows = [{"contrast": f"{r['a']} - {r['b']}", **{k_: r[k_] for k_ in ("estimate", "se", "stat", "p", "p_adj", "ci_low", "ci_high")}} for r in rows]
descr = [{"group": lv, "n": len(x), "mean": float(x.mean()), "sd": float(x.std(ddof=1)) if len(x) > 1 else None,
"letters": letters.get(lv, "")} for lv, x in zip(levels, groups)]
tables = [{"key": "posthoc", "title": f"{method_label} comparisons", "columns": columns, "rows": table_rows},
{"key": "descriptives", "title": "Group means" + (" and letters (groups sharing a letter do not differ)" if letters else ""),
"columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}]
+ ([{"key": "letters", "label": "Letters", "type": "string"}] if letters else []), "rows": descr}]
if method in RANK:
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
chart = cs.chart("distribution", "raincloud", f"{y} by {g}", {
"y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
"group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=levels)})
else:
chart = cs.chart("differences", "forest", f"Differences in mean {y} ({conf:.0%} {'simultaneous ' if method in ('tukey', 'scheffe', 'games_howell', 'tamhane_t2', 'dunnett_t3', 'uwh', 'dunnett') else ''}CI)", {
"label": cs.col("Contrast", [x["contrast"] for x in table_rows], "categorical"),
"estimate": cs.col(f"Difference in {y}", [x["estimate"] for x in table_rows], "numeric"),
"low": cs.col("CI low", [x["ci_low"] for x in table_rows], "numeric"),
"high": cs.col("CI high", [x["ci_high"] for x in table_rows], "numeric")}, controls={"reference": 0})
charts = [chart]
if letters and k >= 3:
if method in RANK:
# Mean ranks from the joint ranking; groups that share a letter are joined by a bar (Demšar-style).
ranks_all = stats.rankdata(np.concatenate(groups))
cuts = np.cumsum([0] + [len(x) for x in groups])
charts.append(cs.chart("cld", "critical-difference", f"Mean ranks of {y}: groups joined by a bar do not differ", {
"label": cs.col(g, levels, "categorical"),
"rank": cs.col("Mean rank", [float(ranks_all[cuts[i]:cuts[i + 1]].mean()) for i in range(k)], "numeric"),
"letters": cs.col("Letters", [letters.get(lv, "") for lv in levels], "categorical")}))
else:
tq = [float(stats.t.ppf(0.5 + conf / 2, len(x) - 1)) if len(x) > 1 else float("nan") for x in groups]
half = [tq[i] * float(x.std(ddof=1)) / np.sqrt(len(x)) if len(x) > 1 else float("nan") for i, x in enumerate(groups)]
charts.append(cs.chart("cld", "cld-plot", f"Mean {y} by {g} ({conf:.0%} CI): groups sharing a letter do not differ", {
"label": cs.col(g, levels, "categorical"),
"center": cs.col(f"Mean {y}", [float(x.mean()) for x in groups], "numeric"),
"low": cs.col("CI low", [float(x.mean()) - h for x, h in zip(groups, half)], "numeric"),
"high": cs.col("CI high", [float(x.mean()) + h for x, h in zip(groups, half)], "numeric"),
"letters": cs.col("Letters", [letters.get(lv, "") for lv in levels], "categorical")}))
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
cs.publish({
"method": "posthoc.pairwise",
"methodVersion": "1.1.3",
"title": f"Pairwise comparisons: {method_label}",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": N,
"summary": f"{len(signif)} of {len(rows)} {method_label} comparisons are significant at α = {alpha:g} (smallest adjusted {cs.fmt_p(min(p_adj))}).",
"apa": f"{method_label}: smallest adjusted {cs.fmt_p(min(p_adj))}",
"statistics": [{"key": "n_significant", "label": "Significant comparisons", "value": len(signif), "format": "integer"},
{"key": "p_min", "label": "Smallest adjusted p", "value": float(min(p_adj)), "format": "p"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Contrasts are first − second level{' (each group − ' + rows[0]['b'] + ')' if method in MANY_TO_ONE else ''}; α = {alpha:g}."],
"values": values,
"charts": charts,
})
What a wider promise costs
PredictPredict first
On the same PlantGrowth data, Scheffé protects every possible contrast, while Fisher's LSD only runs after a significant omnibus test. Which has the larger critical multiplier?
Reveal
Scheffé: 2.59 against 2.05. Wider promises need wider intervals. Fisher's LSD only protects the family when there are three groups; with more, it needs another procedure.
Choosing from the family
Read| Your situation | Procedures |
|---|---|
| Equal variances, all pairs | TukeyTukey HSDCompares all pairs of group means with family-wise control, assuming equal variances. |
| Equal variances, against one control | DunnettDunnett's testCompares each group with one control group, with more power than all-pairs procedures. |
| Any contrast, chosen later | SchefféScheffé testSimultaneous test of every possible contrast among group means, not only pairs. |
| Unequal variances | Games–HowellGames–Howell testAll-pairs comparisons that do not assume equal variances or equal group sizes., Tamhane T2Tamhane T2Welch t-test for each pair with a Šidák correction for all k(k − 1)/2 comparisons., Dunnett T3Dunnett T3Welch t-tests for all pairs judged against the studentized maximum modulus distribution., Ury–Wiggins–HochbergUry–Wiggins–HochbergWelch t-tests for all pairs with a Bonferroni (Ury–Wiggins) or Hochberg step-up adjustment. |
| Ranks | DunnDunn's testPairwise follow-up to Kruskal–Wallis, using the same pooled ranks and a multiplicity adjustment., Conover–ImanConover–Iman testPairwise comparisons of mean ranks after Kruskal–Wallis, using a t distribution and the residual rank variance., NemenyiNemenyi testThe rank analog of Tukey's test — mean-rank differences against the studentized range with k groups., Steel–DwassDwass–Steel–Critchlow–Fligner testMann–Whitney for each pair, ranked within that pair, made simultaneous with the studentized range. |
| Ranks, against one control | SteelSteel's many-to-one testEach treatment compared with one control by Mann–Whitney, adjusted for the shared control. |
BExplorable · The post hoc family
Which pairwise procedure keeps its promise, and when does Tukey fail?
With no true differences, how often do unprotected t tests find something?
Commit your prediction above to see the result
Make your prediction to see the result.
Check your understanding
CheckpointCheck yourself
How many pairwise comparisons are there among 5 groups?
Show the answer
Answer: 10
.
Check yourself
Four new formulations are each compared with one standard formulation, and variances look equal. Which is the most powerful procedure that fits?
Show the answer
Answer: b
A smaller family needs a smaller correction. Tukey spends power on comparisons among the new formulations that you never asked about.
Check yourself
Your groups have clearly different variances and unequal sizes. Which is a sound choice?
Show the answer
Answer: c
Games–Howell uses a Welch-type standard error for each pair. Tukey's pooled variance misleads when variances and sizes differ together.
Families in CodeSplash
In the appEvery test you run is recorded. Open Analyze and choose Multiple testing in the rail: each family has a card, and each dataset starts with an exploratory one. For planned hypotheses, press New family, make it confirmatory, pick an error rate and adjustment, and lock it. Open a family to see the adjusted p-value next to each test.
from statsmodels.stats.multitest import multipletests
pvals = [0.001, 0.015, 0.040, 0.300]
reject, adjusted, _, _ = multipletests(pvals, alpha=0.05, method="holm")
print(reject, adjusted)pvals <- c(0.001, 0.015, 0.040, 0.300)
p.adjust(pvals, method = "holm")Notebook exercise · ~8 min
Holm adjusted p-values in code
Adjust five p-values with Holm's method, keep them in their original order, and count what survives.
- Holm adjusted p-values
Store the Holm adjusted p-values in
p_holm, in the same order asp.Show a solution
Pythonp_holm = multipletests(p, method="holm")[1]Rp_holm <- p.adjust(p, method = "holm") - How many survive
Store the number of outcomes whose Holm adjusted p-value is below
alphainn_reject.Show a solution
Pythonn_reject = int((p_holm < alpha).sum())Rn_reject <- sum(p_holm < alpha)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Recap
Recap- With independent true nulls, the chance of a false alarm is .
- Prefer Holm to Bonferroni; prefer a procedure built for your family, such as Tukey or Dunnett, to either.
- Smaller families cost less, so decide what belongs together before you see the results.
Concepts in this lesson