Stratified tables: Cochran–Mantel–Haenszel, Breslow–Day and Woolf
Combine 2 × 2 tables across strata into one test and one odds ratio, then check whether a single odds ratio is a fair summary of them.
What runs in CodeSplash
- STAT069Cochran–Mantel–Haenszel test Runs in CodeSplash
- STAT070Breslow–Day test Runs in CodeSplash
- STAT071Woolf homogeneity test Runs in CodeSplash
- Cochran–Mantel–Haenszel test (stratified 2 × 2) Verified in Python and R
You will be able to
- Explain how the CMH statistic combines strata
- Say why strata that disagree in direction can cancel out
- Test for a common odds ratio with Breslow–Day or Woolf, and report per stratum when it fails
One comparison per stratum
ReadThe Berkeley data are six 2 × 2 tables, one per department. Within stratum , compare the count in the first cell with , the count you'd expect if group and outcome were unrelated there.
The Mantel–HaenszelMantel–Haenszel poolingCommon-effect pooling of two-arm counts with weights that need no continuity correction for zero cells. statistic adds those gaps across strata, then squares the total:
Here and are the stratum's first row and column totals, and is the variance of under the null. The statistic has 1 degree of freedom, however many strata there are.
Predict the sum
PredictPredict first
Two strata of equal size. In one, a treatment strongly raises the event rate. In the other, it strongly lowers it. What does the CMH statistic do?
Reveal
Near zero. The gaps are added before squaring, so opposite effects cancel. CMH looks for one consistent direction across strata, so a small value doesn't show that nothing is happening inside them.
Run it on Berkeley
Readχ²_MH(1, N = 4526) = 1.52, p = .217, OR_MH = 0.90, 95% CI [0.77, 1.06]
- CMH χ²
- 1.525
- p
- .217
- Breslow–Day χ²
- 18.826
- p (Breslow–Day)
- .002
- Woolf χ²
- 17.902
- p (Woolf)
- .003
Effect size
- Mantel–Haenszel odds ratio 0.9047 95% CI [0.7719, 1.060]
- Crude odds ratio (strata pooled) 1.841
Plots
View data
| Odds ratio | estimate | high | dept | low |
|---|---|---|---|---|
| 0.3492 | stratum | 0.5844 | A | 0.2087 |
| 0.8025 | stratum | 1.892 | B | 0.3404 |
| 1.133 | stratum | 1.502 | C | 0.8545 |
| 0.9213 | stratum | 1.237 | D | 0.6863 |
| 1.222 | stratum | 1.809 | E | 0.8251 |
| 0.8279 | stratum | 1.506 | F | 0.4552 |
| 0.9047 | pooled | 1.060 | Mantel–Haenszel | 0.7719 |
Assumptions
- Common odds ratio across strata — Breslow–Day χ²(5) = 18.83, p = .002; the odds ratios differ, so report them per stratum.
- Informative strata — All 6 strata have both groups.
Odds ratios by dept (Woolf intervals)
| dept | Admitted in Male | n Male | Admitted in Female | n Female | Odds ratio | CI low | CI high |
|---|---|---|---|---|---|---|---|
| A | 512 | 825 | 89 | 108 | 0.3492 | 0.2087 | 0.5844 |
| B | 353 | 560 | 17 | 25 | 0.8025 | 0.3404 | 1.892 |
| C | 120 | 325 | 202 | 593 | 1.133 | 0.8545 | 1.502 |
| D | 138 | 417 | 131 | 375 | 0.9213 | 0.6863 | 1.237 |
| E | 53 | 191 | 94 | 393 | 1.222 | 0.8251 | 1.809 |
| F | 22 | 373 | 24 | 341 | 0.8279 | 0.4552 | 1.506 |
- Odds of admit = Admitted in Male vs Female; Tarone-corrected Breslow–Day χ² = 18.826, p = .002.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cochran–Mantel–Haenszel test (stratified 2 × 2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.cmh 1.1.2 · spec ea94bd9ccc36f13a
# Dataset: ucb_admissions (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_breslow_day, cs_odds_ratio_woolf, cs_woolf_homogeneity (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ucb_admissions.parquet", col_select = c("gender", "admit", "dept")))
n_input <- nrow(df)
df[["gender"]] <- factor(df[["gender"]], levels = c("Male", "Female")) # stored level order
df[["admit"]] <- factor(df[["admit"]], levels = c("Admitted", "Rejected")) # stored level order
df[["dept"]] <- factor(df[["dept"]], levels = c("A", "B", "C", "D", "E", "F")) # stored level order
df <- df[stats::complete.cases(df[c("gender", "admit", "dept")]), , 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("gender", "admit", "dept")) # infinite values stop the run (registry/errors.yaml)
# %% Test
g <- "gender"
y <- "admit"
s <- "dept"
groups <- levels(df[[g]])
if (length(groups) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(groups))
outcome_levels <- c("Admitted", "Rejected") # stored level order
event <- "Admitted" # default: the last level
if (!event %in% outcome_levels) cs_error("CS_E_NOT_A_LEVEL", level = event, column = y)
correct <- FALSE # pinned: no continuity correction (mantelhaen.test defaults to TRUE)
conf <- 0.95
hit <- as.character(df[[y]]) == event
cells <- list()
strata <- character(0)
dropped <- character(0)
for (lv in levels(df[[s]])) { # stored level order
in_s <- df[[s]] == lv
x1 <- sum(hit & in_s & df[[g]] == groups[1])
n1 <- sum(in_s & df[[g]] == groups[1])
x2 <- sum(hit & in_s & df[[g]] == groups[2])
n2 <- sum(in_s & df[[g]] == groups[2])
if (n1 == 0 || n2 == 0) { # one group only: no information about the association
dropped <- c(dropped, lv)
next
}
cells[[length(cells) + 1]] <- c(x1, x2, n1 - x1, n2 - x2)
strata <- c(strata, lv)
}
if (length(cells) < 2) {
cs_error("CS_E_UNDEFINED", what = "The Cochran–Mantel–Haenszel test", reason = sprintf("fewer than two strata of %s have both groups present", s))
}
tab <- array(unlist(cells), dim = c(2, 2, length(cells))) # [group, event/non-event, stratum]
mh <- mantelhaen.test(tab, correct = correct, conf.level = conf) # CMH χ², MH odds ratio, RGB interval
mh_or <- unname(mh$estimate)
bd <- cs_breslow_day(tab, mh_or) # Breslow-Day + Tarone
woolf <- cs_woolf_homogeneity(tab) # Woolf's test of equal log odds ratios
homogeneity_test <- "breslow_day"
hom <- switch(homogeneity_test,
breslow_day = list("Breslow–Day", bd$chi2, bd$df, bd$p),
tarone = list("Breslow–Day (Tarone)", bd$tarone_chi2, bd$df, bd$tarone_p),
woolf = list("Woolf", woolf$chi2, woolf$df, woolf$p))
crude <- apply(tab, c(1, 2), sum)
crude_or <- if (crude[1, 2] * crude[2, 1] > 0) crude[1, 1] * crude[2, 2] / (crude[1, 2] * crude[2, 1]) else Inf
n <- sum(tab)
# %% Assumptions
assumptions <- list(
list(key = "homogeneity", label = "Common odds ratio across strata", status = if (hom[[4]] < 0.05) "warn" else "pass",
detail = paste0(sprintf("%s χ²(%d) = %.2f, %s", hom[[1]], as.integer(hom[[3]]), hom[[2]], cs_fmt_p(hom[[4]])),
if (hom[[4]] < 0.05) "; the odds ratios differ, so report them per stratum." else ".",
if (homogeneity_test == "woolf" && woolf$corrected) " 0.5 was added to every cell for Woolf's test because a cell is empty." else "")),
list(key = "strata_size", label = "Informative strata", status = if (length(dropped)) "warn" else "pass",
detail = if (length(dropped)) paste0("Left out (one group only): ", paste(dropped, collapse = ", "), ".") else sprintf("All %d strata have both groups.", length(strata)))
)
# %% Result
per <- lapply(seq_along(strata), function(i) {
t <- tab[, , i]
w <- cs_odds_ratio_woolf(t[1, 1], t[1, 2], t[2, 1], t[2, 2], conf)
list(stratum = strata[i], a = t[1, 1], n1 = t[1, 1] + t[1, 2], c = t[2, 1], n2 = t[2, 1] + t[2, 2], or = w$or, low = w$low, high = w$high)
})
values <- list(n = n, strata = length(strata), cmh_chi2 = unname(mh$statistic), p = mh$p.value, mh_or = mh_or,
mh_or_ci_low = mh$conf.int[1], mh_or_ci_high = mh$conf.int[2], bd_chi2 = bd$chi2, bd_df = bd$df, bd_p = bd$p,
tarone_chi2 = bd$tarone_chi2, tarone_p = bd$tarone_p, crude_or = crude_or, event = event,
woolf_chi2 = woolf$chi2, woolf_df = woolf$df, woolf_p = woolf$p, woolf_corrected = woolf$corrected,
homogeneity_p = hom[[4]], homogeneity_label = hom[[1]],
level_1 = groups[1], level_2 = groups[2], dropped_strata = length(dropped))
for (r in per) values[[sprintf("or[%s]", r$stratum)]] <- r$or
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "proportion.cmh",
methodVersion = "1.1.2",
title = "Cochran–Mantel–Haenszel test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = sprintf("Common odds ratio %.2f, %s CI [%.2f, %.2f] across %d strata of %s (crude %.2f); CMH χ² = %.2f, %s.",
mh_or, pct, mh$conf.int[1], mh$conf.int[2], length(strata), s, crude_or, unname(mh$statistic), cs_fmt_p(mh$p.value)),
apa = sprintf("χ²_MH(1, N = %d) = %s, %s, OR_MH = %s, %s CI [%s, %s]", as.integer(n), cs_fmt_num(unname(mh$statistic)), cs_fmt_p(mh$p.value),
cs_fmt_num(mh_or), pct, cs_fmt_num(mh$conf.int[1]), cs_fmt_num(mh$conf.int[2])),
statistics = list(
list(key = "cmh_chi2", label = "CMH χ²", value = unname(mh$statistic)), list(key = "p", label = "p", value = mh$p.value, format = "p"),
list(key = "bd_chi2", label = "Breslow–Day χ²", value = bd$chi2), list(key = "bd_p", label = "p (Breslow–Day)", value = bd$p, format = "p"),
list(key = "woolf_chi2", label = "Woolf χ²", value = woolf$chi2), list(key = "woolf_p", label = "p (Woolf)", value = woolf$p, format = "p")
),
tables = list(list(
key = "strata", title = sprintf("Odds ratios by %s (Woolf intervals)", s),
columns = list(list(key = "stratum", label = s, type = "string"), list(key = "a", label = sprintf("%s in %s", event, groups[1]), type = "integer"),
list(key = "n1", label = sprintf("n %s", groups[1]), type = "integer"), list(key = "c", label = sprintf("%s in %s", event, groups[2]), type = "integer"),
list(key = "n2", label = sprintf("n %s", groups[2]), type = "integer"), list(key = "or", label = "Odds ratio", type = "number"),
list(key = "low", label = "CI low", type = "number"), list(key = "high", label = "CI high", type = "number")),
rows = per
)),
effectSizes = list(
list(key = "mh_or", label = "Mantel–Haenszel odds ratio", value = mh_or, ciLow = mh$conf.int[1], ciHigh = mh$conf.int[2], ciLevel = conf,
method = "Robins–Breslow–Greenland interval"),
list(key = "crude_or", label = "Crude odds ratio (strata pooled)", value = crude_or)
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Odds of %s = %s in %s vs %s; Tarone-corrected Breslow–Day χ² = %.3f, %s.", y, event, groups[1], groups[2], bd$tarone_chi2, cs_fmt_p(bd$tarone_p))),
charts = list(cs_chart(
"odds_ratios", "forest", sprintf("Odds ratios by %s", s),
list(label = cs_col(s, c(strata, "Mantel–Haenszel")), estimate = cs_col("Odds ratio", c(vapply(per, function(r) r$or, numeric(1)), mh_or)),
low = cs_col("low", c(vapply(per, function(r) r$low, numeric(1)), mh$conf.int[1])),
high = cs_col("high", c(vapply(per, function(r) r$high, numeric(1)), mh$conf.int[2])),
group = cs_col("estimate", c(rep("stratum", length(per)), "pooled"))),
controls = list(reference = 1, log = TRUE)
)),
values = values
))
χ²_MH(1, N = 4526) = 1.52, p = .217, OR_MH = 0.90, 95% CI [0.77, 1.06]
- CMH χ²
- 1.525
- p
- .217
- Breslow–Day χ²
- 18.826
- p (Breslow–Day)
- .002
- Woolf χ²
- 17.902
- p (Woolf)
- .003
Effect size
- Mantel–Haenszel odds ratio 0.9047 95% CI [0.7719, 1.060]
- Crude odds ratio (strata pooled) 1.841
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Common odds ratio across strata — Breslow–Day χ²(5) = 18.83, p = .002; the odds ratios differ, so report them per stratum.
- Informative strata — All 6 strata have both groups.
Odds ratios by dept (Woolf intervals)
| dept | Admitted in Male | n Male | Admitted in Female | n Female | Odds ratio | CI low | CI high |
|---|---|---|---|---|---|---|---|
| A | 512 | 825 | 89 | 108 | 0.3492 | 0.2087 | 0.5844 |
| B | 353 | 560 | 17 | 25 | 0.8025 | 0.3404 | 1.892 |
| C | 120 | 325 | 202 | 593 | 1.133 | 0.8545 | 1.502 |
| D | 138 | 417 | 131 | 375 | 0.9213 | 0.6863 | 1.237 |
| E | 53 | 191 | 94 | 393 | 1.222 | 0.8251 | 1.809 |
| F | 22 | 373 | 24 | 341 | 0.8279 | 0.4552 | 1.506 |
- Odds of admit = Admitted in Male vs Female; Tarone-corrected Breslow–Day χ² = 18.826, p = .002.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cochran–Mantel–Haenszel test (stratified 2 × 2)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.cmh 1.1.2 · spec ea94bd9ccc36f13a
# Dataset: ucb_admissions (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 statsmodels.stats.contingency_tables import StratifiedTable
import codesplash as cs
from codesplash.stats import proportions as csp # Breslow–Day, Woolf odds ratios (twins of codesplashr)
from codesplash.stats import proportions_ext as csx # Woolf homogeneity (twin of cs_woolf_homogeneity)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ucb_admissions.parquet", columns=["gender", "admit", "dept"])
n_input = len(df)
df["gender"] = pd.Categorical(df["gender"], categories=["Male", "Female"]) # stored level order
df["admit"] = pd.Categorical(df["admit"], categories=["Admitted", "Rejected"]) # stored level order
df["dept"] = pd.Categorical(df["dept"], categories=["A", "B", "C", "D", "E", "F"]) # stored level order
df = df.dropna(subset=["gender", "admit", "dept"]) # listwise deletion over the analysis columns
df["gender"] = df["gender"].cat.remove_unused_categories()
df["admit"] = df["admit"].cat.remove_unused_categories()
df["dept"] = df["dept"].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, ["gender", "admit", "dept"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
g, y, s = "gender", "admit", "dept"
groups = [str(v) for v in df[g].cat.categories]
if len(groups) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(groups))
outcome_levels = ["Admitted", "Rejected"] # stored level order
event = "Admitted" # default: the last level
if event not in outcome_levels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=y)
correct = False # pinned: no continuity correction (R's mantelhaen.test defaults to TRUE)
conf = 0.95
hit = df[y].astype(str) == event
tables, strata, dropped = [], [], []
for lv in df[s].cat.categories: # stored level order
in_s = df[s] == lv
x1, n1 = int((hit & in_s & (df[g] == groups[0])).sum()), int((in_s & (df[g] == groups[0])).sum())
x2, n2 = int((hit & in_s & (df[g] == groups[1])).sum()), int((in_s & (df[g] == groups[1])).sum())
if n1 == 0 or n2 == 0: # one group only: no information about the association
dropped.append(str(lv))
continue
tables.append([[x1, n1 - x1], [x2, n2 - x2]])
strata.append(str(lv))
if len(tables) < 2:
cs.cs_error("CS_E_UNDEFINED", what="The Cochran–Mantel–Haenszel test", reason=f"fewer than two strata of {s} have both groups present")
tab = np.array(tables, dtype=float)
st = StratifiedTable([t for t in tab])
cmh = st.test_null_odds(correction=correct) # CMH χ² (= mantelhaen.test)
mh_or = float(st.oddsratio_pooled)
mh_low, mh_high = st.oddsratio_pooled_confint(alpha=1 - conf) # Robins–Breslow–Greenland interval
bd = csp.breslow_day(tab, mh_or) # Breslow–Day + Tarone
woolf = csx.woolf_homogeneity(tab) # Woolf's test of equal log odds ratios (twin of cs_woolf_homogeneity)
homogeneity_test = "breslow_day"
hom = {"breslow_day": ("Breslow–Day", bd["chi2"], bd["df"], bd["p"]), "tarone": ("Breslow–Day (Tarone)", bd["tarone_chi2"], bd["df"], bd["tarone_p"]),
"woolf": ("Woolf", woolf["chi2"], woolf["df"], woolf["p"])}[homogeneity_test]
crude = tab.sum(axis=0)
crude_or = float(crude[0, 0] * crude[1, 1] / (crude[0, 1] * crude[1, 0])) if crude[0, 1] * crude[1, 0] > 0 else float("inf")
n = int(tab.sum())
# %% Assumptions
assumptions = [
{"key": "homogeneity", "label": "Common odds ratio across strata", "status": "warn" if hom[3] < 0.05 else "pass",
"detail": f"{hom[0]} χ²({hom[2]}) = {hom[1]:.2f}, {cs.fmt_p(hom[3])}" + ("; the odds ratios differ, so report them per stratum." if hom[3] < 0.05 else ".")
+ (" 0.5 was added to every cell for Woolf's test because a cell is empty." if homogeneity_test == "woolf" and woolf["corrected"] else "")},
{"key": "strata_size", "label": "Informative strata", "status": "warn" if dropped else "pass",
"detail": ("Left out (one group only): " + ", ".join(dropped) + ".") if dropped else f"All {len(strata)} strata have both groups."},
]
# %% Result
rows, labels, ests, lows, highs, kinds, values_or = [], [], [], [], [], [], {}
for lv, t in zip(strata, tab):
w = csp.odds_ratio_woolf(t[0, 0], t[0, 1], t[1, 0], t[1, 1], conf)
rows.append({"stratum": lv, "a": int(t[0, 0]), "n1": int(t[0].sum()), "c": int(t[1, 0]), "n2": int(t[1].sum()), "or": w["or"], "low": w["low"], "high": w["high"]})
labels.append(lv); ests.append(w["or"]); lows.append(w["low"]); highs.append(w["high"]); kinds.append("stratum")
values_or[f"or[{lv}]"] = w["or"]
labels.append("Mantel–Haenszel"); ests.append(mh_or); lows.append(float(mh_low)); highs.append(float(mh_high)); kinds.append("pooled")
cs.publish({
"method": "proportion.cmh",
"methodVersion": "1.1.2",
"title": "Cochran–Mantel–Haenszel test",
"engine": cs.engine_info("pandas", "numpy", "statsmodels"),
"n": n,
"summary": f"Common odds ratio {mh_or:.2f}, {conf:.0%} CI [{mh_low:.2f}, {mh_high:.2f}] across {len(strata)} strata of {s} (crude {crude_or:.2f}); CMH χ² = {cmh.statistic:.2f}, {cs.fmt_p(cmh.pvalue)}.",
"apa": f"χ²_MH(1, N = {n}) = {cs.fmt_num(cmh.statistic)}, {cs.fmt_p(cmh.pvalue)}, OR_MH = {cs.fmt_num(mh_or)}, {conf:.0%} CI [{cs.fmt_num(mh_low)}, {cs.fmt_num(mh_high)}]",
"statistics": [
{"key": "cmh_chi2", "label": "CMH χ²", "value": float(cmh.statistic)}, {"key": "p", "label": "p", "value": float(cmh.pvalue), "format": "p"},
{"key": "bd_chi2", "label": "Breslow–Day χ²", "value": bd["chi2"]}, {"key": "bd_p", "label": "p (Breslow–Day)", "value": bd["p"], "format": "p"},
{"key": "woolf_chi2", "label": "Woolf χ²", "value": woolf["chi2"]}, {"key": "woolf_p", "label": "p (Woolf)", "value": woolf["p"], "format": "p"},
],
"tables": [{
"key": "strata", "title": f"Odds ratios by {s} (Woolf intervals)",
"columns": [{"key": "stratum", "label": s, "type": "string"}, {"key": "a", "label": f"{event} in {groups[0]}", "type": "integer"},
{"key": "n1", "label": f"n {groups[0]}", "type": "integer"}, {"key": "c", "label": f"{event} in {groups[1]}", "type": "integer"},
{"key": "n2", "label": f"n {groups[1]}", "type": "integer"}, {"key": "or", "label": "Odds ratio", "type": "number"},
{"key": "low", "label": "CI low", "type": "number"}, {"key": "high", "label": "CI high", "type": "number"}],
"rows": rows,
}],
"effectSizes": [{"key": "mh_or", "label": "Mantel–Haenszel odds ratio", "value": mh_or, "ciLow": float(mh_low), "ciHigh": float(mh_high), "ciLevel": conf,
"method": "Robins–Breslow–Greenland interval"},
{"key": "crude_or", "label": "Crude odds ratio (strata pooled)", "value": crude_or}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Odds of {y} = {event} in {groups[0]} vs {groups[1]}; Tarone-corrected Breslow–Day χ² = {bd['tarone_chi2']:.3f}, {cs.fmt_p(bd['tarone_p'])}."],
"charts": [cs.chart(
"odds_ratios", "forest", f"Odds ratios by {s}",
{"label": cs.col(s, labels), "estimate": cs.col("Odds ratio", ests), "low": cs.col("low", lows), "high": cs.col("high", highs),
"group": cs.col("estimate", kinds)},
controls={"reference": 1, "log": True},
)],
"values": {
"n": n, "strata": len(strata), "cmh_chi2": float(cmh.statistic), "p": float(cmh.pvalue), "mh_or": mh_or,
"mh_or_ci_low": float(mh_low), "mh_or_ci_high": float(mh_high), "bd_chi2": bd["chi2"], "bd_df": float(bd["df"]), "bd_p": bd["p"],
"tarone_chi2": bd["tarone_chi2"], "tarone_p": bd["tarone_p"], "crude_or": crude_or, "event": event,
"woolf_chi2": woolf["chi2"], "woolf_df": float(woolf["df"]), "woolf_p": woolf["p"], "woolf_corrected": woolf["corrected"],
"homogeneity_p": hom[3], "homogeneity_label": hom[0],
"level_1": groups[0], "level_2": groups[1], "dropped_strata": len(dropped), **values_or,
},
})
Across 6 departments, the common odds ratio of admission for men against women is 0.90 (95% CI 0.77 to 1.06), with = 1.52, p = .217. The crude odds ratio was 1.84.
CodeSplash leaves out the continuity correction by default. R's mantelhaen.test applies it unless you ask otherwise, which gives 1.43.
Is one odds ratio fair?
ReadHere is each department, worked from its counts. Values below 1 favor women.
| Department | Men admitted | Women admitted | Odds ratio |
|---|---|---|---|
| A | 512 of 825 | 89 of 108 | = 0.35 |
| B | 353 of 560 | 17 of 25 | = 0.80 |
| C | 120 of 325 | 202 of 593 | = 1.13 |
| D | 138 of 417 | 131 of 375 | = 0.92 |
| E | 53 of 191 | 94 of 393 | = 1.22 |
| F | 22 of 373 | 24 of 341 | = 0.83 |
Five departments sit near 1. Department A doesn't.
Predict the check
PredictPredict first
Breslow–DayBreslow–Day testTests whether stratified 2 × 2 tables share one odds ratio, from each stratum's fitted count at the common value. asks what each stratum's first cell would be if all strata shared the Mantel–Haenszel odds ratio, then sums the squared gaps on degrees of freedom. What will it say about these six departments?
Reveal
Not compatible: = 18.83 on 5 df, p = .002. The common odds ratio averages over real differences.
See a pooled value hide a spread
ExploreThis explorable uses studies, which play the same role as strata. Raise the spread of true effects, and watch the pooled estimate stay near the average while it describes fewer of the individual effects.
BExplorable · Forest plots and heterogeneity
When studies disagree, what does a pooled effect mean?
What share of the variation between studies is real (I²)?
Commit your prediction above to see the result
Make your prediction to see the result.
Its statistic is the idea behind Woolf's testWoolf's homogeneity testTests whether the odds ratio is the same in every stratum, from the weighted spread of the stratum log odds ratios.: a weighted spread of the log odds ratios.
Three checks, one question
Read| Test | Works from | Berkeley |
|---|---|---|
| Breslow–Day | Fitted cell counts at the common odds ratio | 18.83 |
| Tarone's correction | Breslow–Day with a small adjustment | 18.83 |
| Woolf | Log odds ratios and their variances | 17.90 |
Woolf needs every cell filled, so CodeSplash adds ½ when one is empty. These tests have little power with few strata or small counts, so a large p-value doesn't show that the odds ratios match.
When the strata agree
ReflectThree centers in the guide's example give odds ratios of 3.50, 3.29 and 3.00. There, Woolf's test gives p = .980, and the common odds ratio of 3.25 (95% CI 1.75 to 6.05) is a fair one-number summary.
At Berkeley it isn't. Without Department A, the other five departments give a common odds ratio close to 1 and a large Breslow–Day p-value, so you'd report A separately.
If you were writing up your own stratified table, what would make you stop trusting the single pooled number?
Check your understanding
CheckpointCheck yourself
A stratum has 100 people, a first-row total of 40 and a first-column total of 30. What is , the expected count in the first cell?
Show the answer
Answer: 12
40 × 30 / 100 = 12.
Check yourself
Three strata have gaps of +4, −4 and +1, with variances 2, 2 and 1. What is the uncorrected CMH statistic?
Show the answer
Answer: 0.2
The gaps sum to 1 and the variances sum to 5, so 1² / 5 = 0.2. Two sizeable gaps canceled.
Check yourself
How many degrees of freedom does Breslow–Day have with 6 strata?
Show the answer
Answer: 5
One fewer than the number of strata: 6 − 1 = 5.
Check yourself
A CMH test gives p = 0.40, and Breslow–Day gives p = 0.002. What should you do?
Show the answer
Answer: b
Breslow–Day says one odds ratio doesn't fit. A small CMH statistic can come from strata canceling, so read the strata before saying anything overall.
Do it in CodeSplash
In the appChoose Groups, Outcome and Strata, then the Event level. Homogeneity test picks which test decides the common-odds-ratio row, and the card reports all three. Continuity correction is off by default. The card also lists the odds ratio in each stratum and the crude one.
import numpy as np
from statsmodels.stats.contingency_tables import StratifiedTable
# One table per department: men and women, by admitted and rejected
depts = [[[512, 313], [89, 19]], [[353, 207], [17, 8]], [[120, 205], [202, 391]],
[[138, 279], [131, 244]], [[53, 138], [94, 299]], [[22, 351], [24, 317]]]
st = StratifiedTable([np.array(t) for t in depts])
print(st.oddsratio_pooled, st.oddsratio_pooled_confint())
print(st.test_null_odds(correction=False)) # CMH
print(st.test_equal_odds()) # Breslow-Day
print(st.test_equal_odds(adjust=True)) # with Tarone's correctionmantelhaen.test(UCBAdmissions, correct = FALSE)
# install.packages("DescTools")
DescTools::BreslowDayTest(UCBAdmissions)
DescTools::WoolfTest(UCBAdmissions)Recap
Recap- CMH adds each stratum's gap before squaring, so it finds consistent association and can miss effects that cancel.
- The Mantel–Haenszel odds ratio is one number; Breslow–Day and Woolf ask whether one number is enough.
- When they say no, report the strata. When they say nothing, remember how little power they have.
Concepts in this lesson