Simpson's paradox and the Berkeley admissions
A gap can vanish or reverse when you split the data. The Berkeley admissions show how, and why the data alone can't say which view is right.
What runs in CodeSplash
- Cochran–Mantel–Haenszel test (stratified 2 × 2) Verified in Python and R
- Two independent proportions (z, Fisher, Boschloo, Barnard, non-inferiority) Verified in Python and R
You will be able to
- Show how a pooled table can reverse within strata
- Explain the role of a confounding variable
- Say why the choice between pooled and stratified needs causal reasoning
The headline
ReadIn 1973, Berkeley's graduate admissions looked biased: men were admitted at 0.45 and women at 0.30. The odds ratio is 1.84, and the test isn't close: p < .001.
But admission decisions are made by departments.
Predict the split
PredictPredict first
The six largest departments are analyzed one at a time. What do you expect?
Reveal
Women are admitted at a higher rate in four of the six. In the most striking case, Department A admitted 89 of 108 women (82%) and 512 of 825 men (62%). The pooled gap has reversed.
How can both be true?
ReadWomen applied mostly to departments that admit few applicants of anyone. Men applied more to departments that admit many.
Department is a confounderConfounderA variable that affects both the treatment and the outcome, creating a spurious association. here: it's related both to gender and to admission. The overall rate for a group is a weighted average of its department rates, and the two groups use very different weights.
Change the weights
ExploreChange which departments each group applies to, leaving each department's admission rates alone. Watch the pooled gap appear, vanish and reverse while no individual department changes its behavior.
EExplorable · Simpson's paradox: Berkeley admissions
Can a comparison reverse when you split the data into groups?
Overall, men were admitted more often. Within departments, who is usually admitted more often?
View
Commit your prediction above to see the result
Make your prediction to see the result.
The stratified answer
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,
},
})
Adjusting for department, the common odds ratio is 0.90 (95% CI 0.77 to 1.06), p = .217. The data are compatible with no gender gap within departments.
The next lesson shows how that adjustment works, and why a single summary may not suit this table.
Which table is right?
ReflectDon't conclude that the stratified result always wins. It depends on the causal story.
If department choice comes before the decision, as here, conditioning on it answers "do departments treat equal applicants alike?". But if a treatment changes which group someone ends up in, stratifying on that group can remove the very effect you want.
Data can't settle this by themselves. In your own analysis, is the stratifying variable a cause of the groups, or a result of them?
Check your understanding
CheckpointCheck yourself
Group W applies 25% of the time to a department admitting 60% and 75% of the time to one admitting 20%. What is group W's overall admission rate?
Show the answer
Answer: 0.3
0.25 × 0.60 + 0.75 × 0.20 = 0.15 + 0.15 = 0.30. Overall rates are weighted averages, and the weights are where the paradox lives.
Check yourself
What does Simpson's paradox require?
Show the answer
Answer: b
It's arithmetic, not a sampling accident. It can happen in a whole population with no noise at all.
Check yourself
A drug lowers blood pressure, and lower blood pressure reduces strokes. Should you stratify on blood pressure measured after treatment to study the drug's effect on strokes?
Show the answer
Answer: b
Here blood pressure is a mediator, not a confounder. The right choice depends on the causal structure, not on the numbers.
Do it in CodeSplash
In the appCompare the crude and adjusted odds ratios directly: the Cochran–Mantel–Haenszel card reports both. If you have a third variable you suspect, add it as Strata.
import pandas as pd
df = pd.read_csv("ucb_admissions.csv")
print(pd.crosstab(df["gender"], df["admit"], normalize="index"))
print(pd.crosstab([df["dept"], df["gender"]], df["admit"], normalize="index"))prop.table(margin.table(UCBAdmissions, 1:2), 2) # pooled, by gender
prop.table(UCBAdmissions, c(2, 3)) # by gender, within each departmentRecap
Recap- A pooled gap can shrink, vanish or reverse within strata, because overall rates are weighted averages.
- The stratified view is right only when the stratifier comes before the groups in the causal story.
- Always ask what the groups differ on besides the thing you care about.
Concepts in this lesson