Observational or experimental?
Who chose the treatment decides what you can claim. See a coin balance what a choice cannot, and watch a famous gap reverse.
What runs in CodeSplash
- Cochran–Mantel–Haenszel test (stratified 2 × 2) Verified in Python and R
You will be able to
- Tell an experiment from an observational study by asking who assigned the treatment
- Explain how a confounder can create or hide an association
- Choose wording that matches the design
Read first
Who chose the treatment?
ReadOne question separates the two kinds of study. In an experimentRandomized experimentA study in which chance decides who gets each treatment, so groups differ only by luck on average. the researcher assigns the treatment, ideally by chance. In an observational studyObservational studyA study in which people or circumstances, not the researcher, decide who gets the treatment. people, or circumstances, choose for themselves.
Why does it matter? Those who choose a treatment often differ from those who don't. Anything that affects both the choice and the outcome is a confounderConfounderA variable that affects both the treatment and the outcome, creating a spurious association., and it can produce a difference even when the treatment does nothing.
A coin against a choice
ExploreBelow, a simulated treatment has a known effect. Switch Who gets treated between A coin decides and People choose, and compare the Average estimate.
Then raise the number of people. Does a larger study rescue the choice?
DExplorable · What randomization balances
Does randomizing guarantee the groups match, and does it reach what you never measured?
In what share of assignments will the groups differ by more than 0.1 SD on the measured covariate?
Who gets treated
Commit your prediction above to see the result
Make your prediction to see the result.
A gap that reverses
ExploreBerkeley's 1973 graduate admissions looked biased: the odds of admission were 1.84 times higher for men, across 4,526 applicants.
Applicants chose their own departments. Switch the view and compare.
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.
What happened in Berkeley
ReadDepartments differ widely in how many applicants they admit, and women applied more often to the most competitive ones. Department confounds the overall comparison.
Compare within departments and the odds ratio for men falls to 0.90 (95% CI 0.77 to 1.06), compatible with no difference overall. Departments are not all alike, though, so read them one at a time too.
χ²_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,
},
})
What each design lets you say
ReadAn experiment lets you talk about what a treatment caused, for the units studied. An observational study shows association, unless a credible design rules out other explanations. Randomizing also has limits.
Check your reading
CheckpointCheck yourself
Customers who use a new feature renew more often than customers who don't. Each customer decided whether to use it. What can you say?
Show the answer
Answer: b
Customers chose the feature, so engagement may drive both. Observational data can still be analyzed, and with a good design they can support stronger claims.
Check yourself
What does random assignment do that adjusting for measured variables can't?
Show the answer
Answer: b
Any one randomization can be unbalanced, especially in small studies. Its guarantee is about the long run, and it covers things you never measured.
Check yourself
What was the odds ratio for men within departments? Give two decimals.
Show the answer
Answer: 0.904696828258623
It is the Mantel–Haenszel estimate, which pools the odds ratios inside each department. Compare it with the overall figure to see how much department mattered.
Try it in the app
In the appIf you have a group, a yes-or-no outcome and a possible confounder, run the stratified comparison. For a causal question on observational data, the Causal studio walks you through a design.
Recap
Recap- Ask who assigned the treatment. That one question separates experiments from observational studies.
- A confounder affects both the treatment and the outcome, and a bigger sample doesn't remove it.
- Randomization balances known and unknown variables on average, not in every study.
- Match your wording to the design: "caused" needs a design that supports it.
Concepts in this lesson