Skip to content

EProportions & counts · proportion.cmh

Cochran–Mantel–Haenszel test (stratified 2 × 2)

Are group and outcome associated after adjusting for a stratifying variable?

Tests the association between two groups and a yes/no outcome across strata (CMH χ²), estimates the common Mantel–Haenszel odds ratio with the Robins–Breslow–Greenland interval, and checks whether the odds ratio is the same in every stratum (Breslow–Day, with Tarone's correction).

Verified in Python and R Python and R agree to 10 decimals Also called Woolf test, Woolf homogeneity test, test of homogeneity of odds ratios…

A real result

Example “Ucb by department”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Cochran–Mantel–Haenszel testRecorded · Python and R agreeRecorded 2026-11-17 · 29 values compared
R

χ²_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

Odds ratios by deptHow large are several estimates, how precise, and which exclude the null?
View data
Odds ratioestimatehighdeptlow
0.3492stratum0.5844A0.2087
0.8025stratum1.892B0.3404
1.133stratum1.502C0.8545
0.9213stratum1.237D0.6863
1.222stratum1.809E0.8251
0.8279stratum1.506F0.4552
0.9047pooled1.060Mantel–Haenszel0.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)

deptAdmitted in Malen MaleAdmitted in Femalen FemaleOdds ratioCI lowCI high
A512825891080.34920.20870.5844
B35356017250.80250.34041.892
C1203252025931.1330.85451.502
D1384171313750.92130.68631.237
E53191943931.2220.82511.809
F22373243410.82790.45521.506
  • Odds of admit = Admitted in Male vs Female; Tarone-corrected Breslow–Day χ² = 18.826, p = .002.
Python

χ²_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)

deptAdmitted in Malen MaleAdmitted in Femalen FemaleOdds ratioCI lowCI high
A512825891080.34920.20870.5844
B35356017250.80250.34041.892
C1203252025931.1330.85451.502
D1384171313750.92130.68631.237
E53191943931.2220.82511.809
F22373243410.82790.45521.506
  • Odds of admit = Admitted in Male vs Female; Tarone-corrected Breslow–Day χ² = 18.826, p = .002.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Ucb by departmentucb_admissions · group: gender · outcome: admit · strata: dept
  • Hair eye blue by hairhair_eye · group: sex · outcome: eye · strata: hair
  • Odds ratio exactly onee_cmh_null · group: arm · outcome: outcome · strata: site
  • Woolf guidee_guide_strata · group: arm · outcome: outcome · strata: centre
  • Woolf ucb taroneucb_admissions · group: gender · outcome: admit · strata: dept
  • Ucb corrected 90ucb_admissions · group: gender · outcome: admit · strata: dept
  • Degenerate single levelucb_admissions · group: gender · outcome: admit · strata: dept

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Two groups, binary outcome: two-proportion z, Fisher's exact · Statistics Guide · B — Compare groups
  • Stratified, repeated, multiway, survey · Statistics Guide · E — Compare proportions / frequencies

What you need

Groupscategorical / boolean · 1 column · 2–2 levels
Exactly two groups; odds ratios compare the first with the second (stored level order).
Outcomecategorical / boolean · 1 column · 2–30 levels
The event level counts as a success; every other level is a non-event.
Stratacategorical / boolean · 1 column · 2–100 levels
The confounder to adjust for (center, department, age band …).

Choices you make

hypothesis

Event leveldefault —

The outcome level counted as the event (default the last stored level).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

options

Continuity correctiondefault off

Subtract ½ from |Σ(a − E[a])| as R's mantelhaen.test does by default; off by default here.

statistics

Homogeneity testdefault breslow_day

Which test decides the "common odds ratio" assumption row. All three are reported.

  • Breslow–Day(default) — Compares each stratum's table with what the common Mantel–Haenszel odds ratio predicts.
  • Breslow–Day with Tarone's correction — Corrects Breslow–Day for using the Mantel–Haenszel estimate; preferred when strata are many and small.
  • Woolf — Weighted variance of the stratum log odds ratios; simple but needs every cell filled (0.5 is added when one is empty).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Common odds ratio across strata

    Breslow–Day test; when the odds ratios differ, report them per stratum instead of pooling.

  • Informative strata

    Strata with only one group carry no information and are left out.

What it reports

  • Tests: Association adjusted for the strata
  • Tests: Odds ratio differs across strata (Breslow–Day)
n
How many independent units the analysis used; it sets precision and power.
strata
Common-effect pooling of two-arm counts with weights that need no continuity correction for zero cells.
cmh_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
p
How surprising your data would be if the null hypothesis were true, as a probability.
mh_or
Common-effect pooling of two-arm counts with weights that need no continuity correction for zero cells.
mh_or_ci_low
A range of effect values compatible with your data at the chosen confidence level.
mh_or_ci_high
A range of effect values compatible with your data at the chosen confidence level.
bd_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
bd_df
How much independent information is left to estimate variability after fitting the model.
bd_p
How surprising your data would be if the null hypothesis were true, as a probability.
tarone_chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
tarone_p
How surprising your data would be if the null hypothesis were true, as a probability.
crude_or
How many times higher the odds of an event are in one group than another; 1 means no difference.
event
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
level_1
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
level_2
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
dropped_strata
Common-effect pooling of two-arm counts with weights that need no continuity correction for zero cells.
woolf_chi2
Tests whether the odds ratio is the same in every stratum, from the weighted spread of the stratum log odds ratios.
woolf_df
How much independent information is left to estimate variability after fitting the model.
woolf_p
Tests whether the odds ratio is the same in every stratum, from the weighted spread of the stratum log odds ratios.
woolf_corrected
Tests whether the odds ratio is the same in every stratum, from the weighted spread of the stratum log odds ratios.
homogeneity_p
How surprising your data would be if the null hypothesis were true, as a probability.
homogeneity_label
Which test checked that the odds ratio is the same in every stratum: Breslow–Day, Breslow–Day (Tarone) or Woolf.

Per group, level or term: or[<stratum>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • CMH χ² and the Mantel–Haenszel odds ratio with the Robins–Breslow–Greenland interval: statsmodels StratifiedTable in Python, mantelhaen.test in R. Breslow–Day is the codesplash twin in both (equal to StratifiedTable.test_equal_odds).
Python

The exact script CodeSplash ran for example “Ucb by department” · 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,
    },
})
R

The exact script CodeSplash ran for example “Ucb by department” · 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
))

Sources

  • Woolf, B. (1955). On estimating the relation between blood group and disease. Annals of Human Genetics, 19, 251–253.
  • Mantel, N., & Haenszel, W. (1959). Statistical aspects of the analysis of data from retrospective studies of disease. JNCI, 22, 719–748.
  • Robins, J., Breslow, N., & Greenland, S. (1986). Estimators of the Mantel–Haenszel variance consistent in both sparse data and large-strata limiting models. Biometrics, 42, 311–323.
  • Breslow, N. E., & Day, N. E. (1980). Statistical Methods in Cancer Research, Vol. 1. IARC.
  • Tarone, R. E. (1985). On heterogeneity tests based on efficient scores. Biometrika, 72, 91–95.

From the CodeSplash method registry · proportion.cmh v1.1.2.