Skip to content

Risks, rates and percentage points

One gap can be 14 points, 47% or 84% depending on the measure. Say the one you mean, give the baseline, use counts people can picture, and check what the gap means.

Applied ~12 min11 steps

What runs in CodeSplash

You will be able to

  • Tell percentage points from percent, and risk ratios from odds ratios
  • Give a baseline with any relative number
  • Rewrite a proportion as a count of people

Read first

01

One gap, three ways to say it

Read

At Berkeley in 1973, 1,198 of 2,691 men were admitted to graduate school (44.5%), and 557 of 1,835 women (30.4%).

MeasureValueIn words
Risk differenceRisk differenceThe difference in event probabilities between groups; the number that matters for decisions.0.142About 14 percentage points higher
Risk ratioRisk ratioThe probability of the event in one group divided by that in another.1.47A 47% higher rate
Odds ratioOdds ratioHow many times higher the odds of an event are in one group than another; 1 means no difference.1.8484% higher odds

All three are true, and they don't sound alike. Choosing one is a decision about what your reader will believe.

02

Read the headline

Predict

Predict first

A news story reads, "Men were 84% more likely to be admitted." Is that right?

Yes, that's what the odds ratio saysNo: the odds were 84% higher, and the rate was 47% higherNo: the rate was 84 points higher
Reveal

No. "More likely" means a ratio of probabilities, and that's the risk ratio. An odds ratio is a ratio of odds, and it overstates the risk ratio when an outcome is common. Admission here is common.

03

See why they part ways

Explore

Set the baseline risk near the women's rate, 30.4%, and the odds ratio to 1.84. Read off the risk ratio.

EExplorable · Odds ratio, risk ratio, risk difference

What does an odds ratio mean for actual risks?

Guess the risk ratio for this odds ratio and baseline risk.

5.00
How sure?
0.400
2.00

Baseline: 100 people

  • Event: 40
  • No event: 60

Exposed: 100 people

  • Event: 57
  • No event: 43

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Now keep the odds ratio and drop the baseline to 1%. The two ratios nearly agree when the outcome is rare, which is why people get away with treating them alike until they can't.

04

Points or percent?

Read

The rate went from 30.4% to 44.5%. As subtraction, that's about 14 percentage pointsPercentage pointThe unit for subtracting one percentage from another. From 20% to 25% is 5 points, which is a 25% relative rise.. As a ratio, it's 47% higher.

"A 14% increase" is wrong: the units came from one and the number from the other. Lift in an A/B test works the same way. The checkout test's 15.2% lift is relative. In points, it's about 2.

05

Halved from what?

Predict

Predict first

"The new drug cuts the risk of the side effect in half." Is that a big benefit?

Yes, half is halfIt depends on the baselineNo, relative risks are always small
Reveal

It depends on the baseline. From 2 in 1,000 to 1 in 1,000 helps one person per thousand. From 40% to 20% helps 200 per thousand. Same ratio, and a very different decision. Give the absolute risk next to any relative one.

06

Count people

Read

Percentages are abstract, and people reason better with counts. Natural frequenciesNatural frequencyA proportion written as a count of people, such as "45 of every 100". People tend to reason better with these. say the same thing as a proportion, with a real denominator:

Of every 100 men who applied, about 45 were admitted. Of every 100 women, about 30 were.

Keep the same denominator on both sides. "1 in 3 versus 2 in 5" makes a reader do arithmetic before they can compare.

For a treatment, number needed to treatNumber needed to treatHow many people must receive the treatment for one extra to benefit; 1 divided by the risk difference. is 1/risk difference1 / \text{risk difference}. It's only sensible when the thing you're comparing is something you could assign.

07

Then ask what the gap means

Explore

So far you've described the gap. Now split the same applicants by department and see what happens.

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.
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
))
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.
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,
    },
})

Within departments, the common odds ratio is 0.90, 95% CI [0.77, 1.06], against 1.84 overall. Women applied more often to departments that admitted fewer people.

An accurate number can still leave a false impression. Report both, and describe which comparison each one makes.

08

Compute all three

Explore
Python
x1, n1, x2, n2 = 1198, 2691, 557, 1835
p1, p2 = x1 / n1, x2 / n2

risk_diff = p1 - p2
risk_ratio = p1 / p2
odds_ratio = (p1 / (1 - p1)) / (p2 / (1 - p2))
print(round(risk_diff, 3), round(risk_ratio, 2), round(odds_ratio, 2))
R
x1 <- 1198; n1 <- 2691; x2 <- 557; n2 <- 1835
p1 <- x1 / n1; p2 <- x2 / n2

risk_diff <- p1 - p2
risk_ratio <- p1 / p2
odds_ratio <- (p1 / (1 - p1)) / (p2 / (1 - p2))
round(c(risk_diff, risk_ratio, odds_ratio), c(3, 2, 2))

Run it, then run the card. The two-sample proportion test reports all three with intervals.

Two independent proportionsRecorded · Python and R agreeRecorded 2026-11-21 · 42 values compared · largest relative difference 1.9e-12
R

two-proportion z test, p < .001, RD = 0.142, 95% CI [0.113, 0.170]

p (two-proportion z test)
< .001
z
9.602
p (z test)
< .001
p (Fisher's exact)
< .001
p (Boschloo's exact)
—
p (Barnard's exact)
—

Effect size

  • Risk difference 0.1416 95% CI [0.1132, 0.1696]
  • Risk ratio 1.467 95% CI [1.352, 1.591]
  • Odds ratio 1.841 95% CI [1.624, 2.087]
  • Odds ratio (conditional MLE) 1.841 95% CI [1.621, 2.091]
  • Cohen's h 0.2940 · small
  • Number needed to treat 7.060 95% CI [5.897, 8.833]

Plots

Proportion with admit = AdmittedHow large are several estimates, how precise, and which exclude the null?

Wilson intervals; the line marks the pooled proportion.

View data
Proportion Admittedhighgenderlow
0.44520.4640Male0.4265
0.30350.3250Female0.2829

Assumptions

  • Expected counts ≥ 5 — Every expected count is at least 5 (smallest 711.54).
  • Independent observations — Each row is a different subject in exactly one group.

Proportion with admit = Admitted

genderEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
Male1,1982,6910.44520.42650.4640
Female5571,8350.30350.28290.3250
  • Event: admit = Admitted; differences are Male − Female; alternative: two-sided.
The exact R script · R R version 4.5.1 (2025-06-13)
# Two independent proportions (z, Fisher, Boschloo, Barnard, non-inferiority)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.two_sample 1.2.0 · spec 6bff1c7fc2215d74
# 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_newcombe_diff_ci, cs_risk_ratio, cs_odds_ratio_woolf, cs_boschloo, cs_barnard, cs_fm_hypothesis (twins of codesplash.stats)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ucb_admissions.parquet", col_select = c("gender", "admit")))
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 <- df[stats::complete.cases(df[c("gender", "admit")]), , 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"))  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
  # Benchmark label for an effect size (rule set named in the result)
  if (is.null(x) || !is.finite(x)) return("undetermined")
  labels[findInterval(abs(x), cuts) + 1]
}

# %% Test
g <- "gender"
y <- "admit"
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 ("true")
if (!event %in% outcome_levels) cs_error("CS_E_NOT_A_LEVEL", level = event, column = y)
hit <- as.character(df[[y]]) == event
x1 <- sum(hit[df[[g]] == groups[1]])
n1 <- sum(df[[g]] == groups[1])
x2 <- sum(hit[df[[g]] == groups[2]])
n2 <- sum(df[[g]] == groups[2])
n <- n1 + n2
alternative <- "two-sided"
conf <- 0.95
test <- "z"
correct <- FALSE  # pinned: no Yates correction unless asked (prop.test defaults to TRUE)

# Pooled two-proportion z test (exactly prop.test(c(x1, x2), c(n1, n2), correct = ...))
zt <- cs_two_prop_z(x1, n1, x2, n2, alternative = alternative, correct = correct)
# Fisher's exact test and the conditional-MLE odds ratio
ft <- fisher.test(matrix(c(x1, x2, n1 - x1, n2 - x2), nrow = 2), alternative = sub("-", ".", alternative, fixed = TRUE),
                  conf.level = conf)
fisher_p <- ft$p.value
cor <- cs_fisher_or(x1, n1 - x1, x2, n2 - x2, conf, alternative)  # fisher.test's estimate, solved to 1e-12
# Boschloo's unconditional exact test (codesplash twin; up to 1,000 rows)
boschloo_p <- if (n <= 1000) cs_boschloo(x1, n1, x2, n2, alternative = alternative) else NULL
# Barnard's unconditional exact test with the pooled z statistic (codesplash twin; up to 1,000 rows)
barnard_stat <- "pooled"  # Stage 12.7 option: pooled (default) or unpooled z
barnard <- if (n <= 1000) cs_barnard(x1, n1, x2, n2, alternative = alternative, pooled = barnard_stat == "pooled") else NULL
barnard_p <- barnard$p
if (test %in% c("boschloo", "barnard") && n > 1000) {
  warnings <- c(warnings, sprintf("Unconditional exact tests are computed for up to 1,000 rows (%d here); Fisher's exact test is used instead.", n))
  test <- "fisher"
}
labels <- c(z = "two-proportion z test", fisher = "Fisher's exact test", boschloo = "Boschloo's exact test", barnard = "Barnard's exact test")
if (barnard_stat == "unpooled") labels[["barnard"]] <- "Barnard's exact test (unpooled z)"
p <- switch(test, z = zt$p, fisher = fisher_p, boschloo = boschloo_p, barnard = barnard_p)
test_label <- labels[[test]]

# Non-inferiority / equivalence: Farrington-Manning score tests at the margin(s)
hypothesis <- "superiority"
fm <- NULL
if (hypothesis != "superiority") {
  scale <- "difference"
  margin <- if (scale == "difference") 0.1 else 0.8
  if (scale == "difference" && !(margin > 0 && margin < 1)) stop("The non-inferiority margin for a difference must be between 0 and 1 (e.g. 0.1 = 10 percentage points).")
  if (scale == "ratio" && !(margin > 0 && margin != 1)) stop("The margin for a risk ratio must be a positive ratio other than 1 (e.g. 0.8).")
  better <- "higher"
  fm <- cs_fm_hypothesis(x1, n1, x2, n2, hypothesis, margin, scale, if (better == "higher") "greater" else "less")
  p <- fm$p
  test_label <- if (hypothesis == "noninferiority") "Farrington–Manning non-inferiority test" else "Farrington–Manning equivalence test (two one-sided)"
}

# Effect sizes
p1 <- x1 / n1
p2 <- x2 / n2
rd <- p1 - p2
rd_ci <- cs_newcombe_diff_ci(x1, n1, x2, n2, conf)  # Newcombe hybrid score (method 10)
rr <- cs_risk_ratio(x1, n1, x2, n2, conf)  # Katz log interval
orw <- cs_odds_ratio_woolf(x1, n1 - x1, x2, n2 - x2, conf)  # Woolf log interval
h <- 2 * asin(sqrt(p1)) - 2 * asin(sqrt(p2))  # Cohen's h
nnt <- if (rd != 0) 1 / abs(rd) else Inf
nnt_ci <- if (rd_ci[1] > 0 || rd_ci[2] < 0) sort(c(1 / abs(rd_ci[1]), 1 / abs(rd_ci[2]))) else NULL

# %% Assumptions
pooled <- (x1 + x2) / n
min_expected <- min(c(n1 * pooled, n1 * (1 - pooled), n2 * pooled, n2 * (1 - pooled)))
if (!is.null(fm)) {
  if (min_expected < 5) {
    status <- "warn"
    detail <- sprintf("Smallest expected count %.2f (< 5): the score test's normal approximation may be off.", min_expected)
  } else {
    status <- "pass"
    detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", min_expected)
  }
} else if (test != "z") {
  status <- "info"
  lab <- labels[[test]]
  detail <- sprintf("%s%s is exact, so expected counts do not matter (smallest %.2f).", toupper(substr(lab, 1, 1)), substring(lab, 2), min_expected)
} else if (min_expected < 5) {
  status <- "warn"
  detail <- sprintf("Smallest expected count %.2f (< 5): the z test's p-value may be off; use Fisher's or Boschloo's exact test.", min_expected)
} else {
  status <- "pass"
  detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", min_expected)
}
assumptions <- list(
  list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail),
  list(key = "independence", label = "Independent observations", status = "info", detail = "Each row is a different subject in exactly one group.")
)
notes <- list(sprintf("Event: %s = %s; differences are %s − %s; alternative: %s.", y, event, groups[1], groups[2], alternative))
if (rr$corrected || orw$corrected) notes <- c(notes, "A cell is empty, so 0.5 was added to every cell for the risk ratio and the Woolf odds ratio.")
if (!is.null(fm)) {
  what <- if (scale == "difference") "risk difference" else "risk ratio"
  bound <- if (hypothesis == "equivalence") sprintf("[%s, %s]", cs_fmt_num(fm$bound_low), cs_fmt_num(fm$bound_high)) else
    cs_fmt_num(if (better == "higher") fm$bound_low else fm$bound_high)
  notes <- c(notes, sprintf("%s: the %s %s vs %s is tested against %s with restricted maximum-likelihood variances (%s is better).",
                            test_label, what, groups[1], groups[2], bound, if (better == "higher") "higher" else "lower"))
}
if (is.null(nnt_ci)) notes <- c(notes, "The risk-difference interval includes 0, so the NNT interval runs through infinity (benefit to harm) and is not reported.")

# %% Result
alpha <- 1 - conf
size <- magnitude(h, c(0.2, 0.5, 0.8))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("%d/%d (%.1f%%) in %s vs %d/%d (%.1f%%) in %s: risk difference %.3f, %s CI [%.3f, %.3f]; %s %s.",
                   x1, n1, 100 * p1, groups[1], x2, n2, 100 * p2, groups[2], rd, pct, rd_ci[1], rd_ci[2], test_label, cs_fmt_p(p))
if (!is.null(fm)) {
  summary <- paste(summary, sprintf("%s %s at the %s.", if (hypothesis == "equivalence") "Equivalence" else "Non-inferiority",
                                    if (p < alpha) "is shown" else "is not shown", if (hypothesis == "equivalence") "margins" else "margin"))
}
props <- do.call(rbind, lapply(1:2, function(i) {
  x <- c(x1, x2)[i]
  m <- c(n1, n2)[i]
  ci <- cs_prop_ci(x, m, conf, "wilson")
  data.frame(group = groups[i], events = x, n = m, proportion = x / m, ci_low = ci[1], ci_high = ci[2])
}))
cs_publish(list(
  method = "proportion.two_sample",
  methodVersion = "1.2.0",
  title = "Two independent proportions",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = if (is.null(fm)) {
    sprintf("%s, %s, RD = %s, %s CI [%s, %s]", test_label, cs_fmt_p(p), cs_fmt_num(rd, 3), pct, cs_fmt_num(rd_ci[1], 3), cs_fmt_num(rd_ci[2], 3))
  } else {
    zz <- if (!is.null(fm$p_low) && (is.null(fm$p_high) || fm$p_low >= fm$p_high)) fm$z_low else fm$z_high
    sprintf("%s, z = %s, %s, RD = %s, %s CI [%s, %s]", test_label, cs_fmt_num(zz), cs_fmt_p(p), cs_fmt_num(rd, 3), pct,
            cs_fmt_num(rd_ci[1], 3), cs_fmt_num(rd_ci[2], 3))
  },
  statistics = c(list(
    list(key = "p", label = sprintf("p (%s)", test_label), value = p, format = "p"),
    list(key = "z", label = "z", value = zt$z),
    list(key = "p_z", label = "p (z test)", value = zt$p, format = "p"),
    list(key = "fisher_p", label = "p (Fisher's exact)", value = fisher_p, format = "p"),
    list(key = "boschloo_p", label = "p (Boschloo's exact)", value = boschloo_p, format = "p"),
    list(key = "barnard_p", label = "p (Barnard's exact)", value = barnard_p, format = "p")),
    if (!is.null(fm$p_low)) list(list(key = "fm_z_low", label = "z at the lower margin", value = fm$z_low),
                                 list(key = "fm_p_low", label = "p (lower margin)", value = fm$p_low, format = "p")),
    if (!is.null(fm$p_high)) list(list(key = "fm_z_high", label = "z at the upper margin", value = fm$z_high),
                                  list(key = "fm_p_high", label = "p (upper margin)", value = fm$p_high, format = "p"))
  ),
  tables = list(list(
    key = "proportions", title = sprintf("Proportion with %s = %s", y, event),
    columns = list(
      list(key = "group", label = g, type = "string"), list(key = "events", label = "Events", type = "integer"),
      list(key = "n", label = "n", type = "integer"), list(key = "proportion", label = "Proportion", type = "number"),
      list(key = "ci_low", label = sprintf("%s CI low (Wilson)", pct), type = "number"),
      list(key = "ci_high", label = sprintf("%s CI high (Wilson)", pct), type = "number")
    ),
    rows = props
  )),
  effectSizes = list(
    list(key = "risk_diff", label = "Risk difference", value = rd, ciLow = rd_ci[1], ciHigh = rd_ci[2], ciLevel = conf, method = "Newcombe hybrid score (method 10)"),
    list(key = "risk_ratio", label = "Risk ratio", value = rr$rr, ciLow = rr$low, ciHigh = rr$high, ciLevel = conf, method = "Katz log interval"),
    list(key = "odds_ratio", label = "Odds ratio", value = orw$or, ciLow = orw$low, ciHigh = orw$high, ciLevel = conf, method = "Woolf log interval"),
    list(key = "cond_or", label = "Odds ratio (conditional MLE)", value = cor$or, ciLow = cor$low,
         ciHigh = cor$high, ciLevel = conf, method = "Fisher's exact test"),
    list(key = "cohens_h", label = "Cohen's h", value = h, method = "2·asin√p1 − 2·asin√p2", magnitude = size, ruleSet = "Cohen (1988)"),
    list(key = "nnt", label = "Number needed to treat", value = nnt, ciLow = if (is.null(nnt_ci)) NULL else nnt_ci[1],
         ciHigh = if (is.null(nnt_ci)) NULL else nnt_ci[2], ciLevel = conf, method = "1 / |RD| (Altman 1998)")
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(cs_chart(
    "proportions", "forest", sprintf("Proportion with %s = %s", y, event),
    list(label = cs_col(g, groups), estimate = cs_col(paste("Proportion", event), props$proportion),
         low = cs_col("low", props$ci_low), high = cs_col("high", props$ci_high)),
    controls = list(reference = pooled),
    note = "Wilson intervals; the line marks the pooled proportion."
  )),
  values = c(list(
    n = n, n_1 = n1, n_2 = n2, x_1 = x1, x_2 = x2, p_1 = p1, p_2 = p2,
    risk_diff = rd, rd_ci_low = rd_ci[1], rd_ci_high = rd_ci[2],
    z = zt$z, chi2 = zt$chi2, p_z = zt$p, fisher_p = fisher_p,
    cond_or = cor$or, cond_or_ci_low = cor$low, cond_or_ci_high = cor$high,
    boschloo_p = boschloo_p, barnard_p = barnard_p, barnard_z = barnard$z, p = p,
    fm_z_low = fm$z_low, fm_p_low = fm$p_low, fm_z_high = fm$z_high, fm_p_high = fm$p_high,
    margin_low = fm$bound_low, margin_high = fm$bound_high,
    odds_ratio = orw$or, or_ci_low = orw$low, or_ci_high = orw$high,
    risk_ratio = rr$rr, rr_ci_low = rr$low, rr_ci_high = rr$high,
    nnt = nnt, nnt_ci_low = if (is.null(nnt_ci)) NULL else nnt_ci[1], nnt_ci_high = if (is.null(nnt_ci)) NULL else nnt_ci[2],
    cohens_h = h, min_expected = min_expected,
    level_1 = groups[1], level_2 = groups[2], event = event, test_label = test_label
  ), if (barnard_stat != "pooled") list(barnard_statistic = barnard_stat) else list())
))
Python

two-proportion z test, p < .001, RD = 0.142, 95% CI [0.113, 0.170]

p (two-proportion z test)
< .001
z
9.602
p (z test)
< .001
p (Fisher's exact)
< .001
p (Boschloo's exact)
—
p (Barnard's exact)
—

Effect size

  • Risk difference 0.1416 95% CI [0.1132, 0.1696]
  • Risk ratio 1.467 95% CI [1.352, 1.591]
  • Odds ratio 1.841 95% CI [1.624, 2.087]
  • Odds ratio (conditional MLE) 1.841 95% CI [1.621, 2.091]
  • Cohen's h 0.2940 · small
  • Number needed to treat 7.060 95% CI [5.897, 8.833]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Expected counts ≥ 5 — Every expected count is at least 5 (smallest 711.54).
  • Independent observations — Each row is a different subject in exactly one group.

Proportion with admit = Admitted

genderEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
Male1,1982,6910.44520.42650.4640
Female5571,8350.30350.28290.3250
  • Event: admit = Admitted; differences are Male − Female; alternative: two-sided.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Two independent proportions (z, Fisher, Boschloo, Barnard, non-inferiority)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.two_sample 1.2.0 · spec 6bff1c7fc2215d74
# 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 math

import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import proportions as csp  # Newcombe / Katz / Woolf / Boschloo (twins of codesplashr)
from codesplash.stats import proportions_ext as csx  # Barnard, Farrington–Manning (twins of cs_barnard, cs_fm_hypothesis)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/ucb_admissions.parquet", columns=["gender", "admit"])
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 = df.dropna(subset=["gender", "admit"])  # listwise deletion over the analysis columns
df["gender"] = df["gender"].cat.remove_unused_categories()
df["admit"] = df["admit"].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"])  # infinite values stop the run (registry/errors.yaml)

# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
    """Benchmark label for an effect size (rule set named in the result)."""
    if x is None or not np.isfinite(x):
        return "undetermined"
    for cut, label in zip(cuts, labels):
        if abs(x) < cut:
            return label
    return labels[-1]

# %% Test
g, y = "gender", "admit"
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 ("true")
if event not in outcome_levels:
    cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=y)
hit = df[y].astype(str) == event
x1, n1 = int(hit[df[g] == groups[0]].sum()), int((df[g] == groups[0]).sum())
x2, n2 = int(hit[df[g] == groups[1]].sum()), int((df[g] == groups[1]).sum())
n = n1 + n2
alternative = "two-sided"
conf = 0.95
test = "z"
correct = False  # pinned: no Yates correction unless asked (R's prop.test defaults to TRUE)

# Pooled two-proportion z test (exactly R's prop.test(c(x1, x2), c(n1, n2), correct = ...))
zt = csp.two_prop_z(x1, n1, x2, n2, alternative=alternative, correct=correct)
# Fisher's exact test and the conditional-MLE odds ratio (R's fisher.test)
table = np.array([[x1, n1 - x1], [x2, n2 - x2]])
fisher_p = float(stats.fisher_exact(table, alternative=alternative)[1])
cor = stats.contingency.odds_ratio(table, kind="conditional")
cor_ci = cor.confidence_interval(confidence_level=conf, alternative=alternative)
# Boschloo's unconditional exact test (codesplash twin; up to 1,000 rows)
boschloo_p = csp.boschloo(x1, n1, x2, n2, alternative=alternative) if n <= 1000 else None
# Barnard's unconditional exact test with the pooled z statistic (codesplash twin; up to 1,000 rows)
barnard_stat = "pooled"  # Stage 12.7 option: pooled (default) or unpooled z
barnard = csx.barnard(x1, n1, x2, n2, alternative=alternative, pooled=barnard_stat == "pooled") if n <= 1000 else None
barnard_p = barnard["p"] if barnard else None
if test in ("boschloo", "barnard") and n > 1000:
    warnings.append(f"Unconditional exact tests are computed for up to 1,000 rows ({n} here); Fisher's exact test is used instead.")
    test = "fisher"
labels = {"z": "two-proportion z test", "fisher": "Fisher's exact test", "boschloo": "Boschloo's exact test", "barnard": "Barnard's exact test"}
if barnard_stat == "unpooled":
    labels["barnard"] = "Barnard's exact test (unpooled z)"
p = {"z": zt["p"], "fisher": fisher_p, "boschloo": boschloo_p, "barnard": barnard_p}[test]
test_label = labels[test]

# Non-inferiority / equivalence: Farrington–Manning score tests at the margin(s)
hypothesis = "superiority"
fm = None
if hypothesis != "superiority":
    scale = "difference"
    margin = 0.1 if scale == "difference" else 0.8
    if scale == "difference" and not 0 < margin < 1:
        raise ValueError("The non-inferiority margin for a difference must be between 0 and 1 (e.g. 0.1 = 10 percentage points).")
    if scale == "ratio" and not (margin > 0 and margin != 1):
        raise ValueError("The margin for a risk ratio must be a positive ratio other than 1 (e.g. 0.8).")
    better = "higher"
    fm = csx.fm_hypothesis(x1, n1, x2, n2, hypothesis, margin, scale, "greater" if better == "higher" else "less")
    p = fm["p"]
    test_label = "Farrington–Manning non-inferiority test" if hypothesis == "noninferiority" else "Farrington–Manning equivalence test (two one-sided)"

# Effect sizes
p1, p2 = x1 / n1, x2 / n2
rd = p1 - p2
rd_low, rd_high = csp.newcombe_diff_ci(x1, n1, x2, n2, conf)  # Newcombe hybrid score (method 10)
rr = csp.risk_ratio(x1, n1, x2, n2, conf)  # Katz log interval
orw = csp.odds_ratio_woolf(x1, n1 - x1, x2, n2 - x2, conf)  # Woolf log interval
h = 2 * math.asin(math.sqrt(p1)) - 2 * math.asin(math.sqrt(p2))  # Cohen's h
nnt = 1 / abs(rd) if rd != 0 else math.inf
if rd_low > 0 or rd_high < 0:  # the interval excludes 0: invert it (Altman 1998)
    nnt_low, nnt_high = sorted((1 / abs(rd_low), 1 / abs(rd_high)))
else:
    nnt_low = nnt_high = None

# %% Assumptions
pooled = (x1 + x2) / n
expected = np.array([n1 * pooled, n1 * (1 - pooled), n2 * pooled, n2 * (1 - pooled)])
min_expected = float(expected.min())
if fm is not None:
    status, detail = ("warn", f"Smallest expected count {min_expected:.2f} (< 5): the score test's normal approximation may be off.") if min_expected < 5 \
        else ("pass", f"Every expected count is at least 5 (smallest {min_expected:.2f}).")
elif test != "z":
    status, detail = "info", f"{labels[test].capitalize()} is exact, so expected counts do not matter (smallest {min_expected:.2f})."
elif min_expected < 5:
    status, detail = "warn", f"Smallest expected count {min_expected:.2f} (< 5): the z test's p-value may be off; use Fisher's or Boschloo's exact test."
else:
    status, detail = "pass", f"Every expected count is at least 5 (smallest {min_expected:.2f})."
assumptions = [
    {"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail},
    {"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each row is a different subject in exactly one group."},
]
notes = [f"Event: {y} = {event}; differences are {groups[0]} − {groups[1]}; alternative: {alternative}."]
if rr["corrected"] or orw["corrected"]:
    notes.append("A cell is empty, so 0.5 was added to every cell for the risk ratio and the Woolf odds ratio.")
if fm is not None:
    what = "risk difference" if scale == "difference" else "risk ratio"
    bound = (f"[{cs.fmt_num(fm['bound_low'])}, {cs.fmt_num(fm['bound_high'])}]" if hypothesis == "equivalence"
             else cs.fmt_num(fm["bound_low"] if better == "higher" else fm["bound_high"]))
    notes.append(f"{test_label}: the {what} {groups[0]} vs {groups[1]} is tested against {bound} with restricted maximum-likelihood variances "
                 f"({'higher' if better == 'higher' else 'lower'} is better).")
if nnt_low is None:
    notes.append("The risk-difference interval includes 0, so the NNT interval runs through infinity (benefit to harm) and is not reported.")

# %% Result
alpha = 1 - conf
size = magnitude(h, (0.2, 0.5, 0.8))
summary = (
    f"{x1}/{n1} ({p1:.1%}) in {groups[0]} vs {x2}/{n2} ({p2:.1%}) in {groups[1]}: risk difference {rd:.3f}, "
    f"{conf:.0%} CI [{rd_low:.3f}, {rd_high:.3f}]; {test_label} {cs.fmt_p(p)}."
)
if fm is not None:
    shown = p < alpha
    summary += (f" {'Equivalence' if hypothesis == 'equivalence' else 'Non-inferiority'} "
                f"{'is shown' if shown else 'is not shown'} at the {'margins' if hypothesis == 'equivalence' else 'margin'}.")
props = []
for lv, x, m in ((groups[0], x1, n1), (groups[1], x2, n2)):
    lo, hi = csp.prop_ci(x, m, conf, "wilson")
    props.append({"group": lv, "events": x, "n": m, "proportion": x / m, "ci_low": lo, "ci_high": hi})
cs.publish({
    "method": "proportion.two_sample",
    "methodVersion": "1.2.0",
    "title": "Two independent proportions",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": (f"{test_label}, {cs.fmt_p(p)}, RD = {cs.fmt_num(rd, 3)}, {conf:.0%} CI [{cs.fmt_num(rd_low, 3)}, {cs.fmt_num(rd_high, 3)}]" if fm is None else
            f"{test_label}, z = {cs.fmt_num(fm['z_low'] if fm['p_low'] is not None and (fm['p_high'] is None or fm['p_low'] >= fm['p_high']) else fm['z_high'])}, "
            f"{cs.fmt_p(p)}, RD = {cs.fmt_num(rd, 3)}, {conf:.0%} CI [{cs.fmt_num(rd_low, 3)}, {cs.fmt_num(rd_high, 3)}]"),
    "statistics": [
        {"key": "p", "label": f"p ({test_label})", "value": p, "format": "p"},
        {"key": "z", "label": "z", "value": zt["z"]},
        {"key": "p_z", "label": "p (z test)", "value": zt["p"], "format": "p"},
        {"key": "fisher_p", "label": "p (Fisher's exact)", "value": fisher_p, "format": "p"},
        {"key": "boschloo_p", "label": "p (Boschloo's exact)", "value": boschloo_p, "format": "p"},
        {"key": "barnard_p", "label": "p (Barnard's exact)", "value": barnard_p, "format": "p"},
    ] + ([{"key": "fm_z_low", "label": "z at the lower margin", "value": fm["z_low"]}, {"key": "fm_p_low", "label": "p (lower margin)", "value": fm["p_low"], "format": "p"}]
         if fm is not None and fm["p_low"] is not None else [])
      + ([{"key": "fm_z_high", "label": "z at the upper margin", "value": fm["z_high"]}, {"key": "fm_p_high", "label": "p (upper margin)", "value": fm["p_high"], "format": "p"}]
         if fm is not None and fm["p_high"] is not None else []),
    "tables": [{
        "key": "proportions", "title": f"Proportion with {y} = {event}",
        "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "events", "label": "Events", "type": "integer"},
                    {"key": "n", "label": "n", "type": "integer"}, {"key": "proportion", "label": "Proportion", "type": "number"},
                    {"key": "ci_low", "label": f"{conf:.0%} CI low (Wilson)", "type": "number"},
                    {"key": "ci_high", "label": f"{conf:.0%} CI high (Wilson)", "type": "number"}],
        "rows": props,
    }],
    "effectSizes": [
        {"key": "risk_diff", "label": "Risk difference", "value": rd, "ciLow": rd_low, "ciHigh": rd_high, "ciLevel": conf, "method": "Newcombe hybrid score (method 10)"},
        {"key": "risk_ratio", "label": "Risk ratio", "value": rr["rr"], "ciLow": rr["low"], "ciHigh": rr["high"], "ciLevel": conf, "method": "Katz log interval"},
        {"key": "odds_ratio", "label": "Odds ratio", "value": orw["or"], "ciLow": orw["low"], "ciHigh": orw["high"], "ciLevel": conf, "method": "Woolf log interval"},
        {"key": "cond_or", "label": "Odds ratio (conditional MLE)", "value": float(cor.statistic), "ciLow": float(cor_ci.low),
         "ciHigh": float(cor_ci.high), "ciLevel": conf, "method": "Fisher's exact test"},
        {"key": "cohens_h", "label": "Cohen's h", "value": h, "method": "2·asin√p1 − 2·asin√p2", "magnitude": size, "ruleSet": "Cohen (1988)"},
        {"key": "nnt", "label": "Number needed to treat", "value": nnt, "ciLow": nnt_low, "ciHigh": nnt_high, "ciLevel": conf, "method": "1 / |RD| (Altman 1998)"},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [cs.chart(
        "proportions", "forest", f"Proportion with {y} = {event}",
        {"label": cs.col(g, groups), "estimate": cs.col(f"Proportion {event}", [r["proportion"] for r in props]),
         "low": cs.col("low", [r["ci_low"] for r in props]), "high": cs.col("high", [r["ci_high"] for r in props])},
        controls={"reference": pooled},
        note="Wilson intervals; the line marks the pooled proportion.",
    )],
    "values": {
        "n": n, "n_1": n1, "n_2": n2, "x_1": x1, "x_2": x2, "p_1": p1, "p_2": p2,
        "risk_diff": rd, "rd_ci_low": rd_low, "rd_ci_high": rd_high,
        "z": zt["z"], "chi2": zt["chi2"], "p_z": zt["p"], "fisher_p": fisher_p,
        "cond_or": float(cor.statistic), "cond_or_ci_low": float(cor_ci.low), "cond_or_ci_high": float(cor_ci.high),
        "boschloo_p": boschloo_p, "barnard_p": barnard_p, "barnard_z": barnard["z"] if barnard else None, "p": p,
        **({"barnard_statistic": barnard_stat} if barnard_stat != "pooled" else {}),
        "fm_z_low": fm["z_low"] if fm else None, "fm_p_low": fm["p_low"] if fm else None,
        "fm_z_high": fm["z_high"] if fm else None, "fm_p_high": fm["p_high"] if fm else None,
        "margin_low": fm["bound_low"] if fm else None, "margin_high": fm["bound_high"] if fm else None,
        "odds_ratio": orw["or"], "or_ci_low": orw["low"], "or_ci_high": orw["high"],
        "risk_ratio": rr["rr"], "rr_ci_low": rr["low"], "rr_ci_high": rr["high"],
        "nnt": nnt, "nnt_ci_low": nnt_low, "nnt_ci_high": nnt_high, "cohens_h": h, "min_expected": min_expected,
        "level_1": groups[0], "level_2": groups[1], "event": event, "test_label": test_label,
    },
})
09

Check your understanding

Checkpoint

Check yourself

A rate rises from 20% to 25%. How many percentage points is that?

Show the answer

Answer: 5

25 − 20 = 5 points. As a relative change it's 25%, since 5 is a quarter of 20.

Check yourself

The admission rates are 44.52% and 30.35%. What is the risk ratio? Give two decimals.

Show the answer

Answer: 1.46664158138672

44.52 / 30.35.

Check yourself

A logistic regression gives an odds ratio of 2 for an outcome with a baseline risk of 40%. What should your sentence say?

Show the answer

Answer: b

With a 40% baseline, odds of 2 bring the risk to about 57%, a risk ratio near 1.4. Twice the odds is not twice the risk.

Check yourself

Which is easiest for a general reader to compare?

Show the answer

Answer: c

The same denominator lets the reader compare at a glance.

10

Your next number

Reflect

Find a percentage in something you wrote recently. Is it a share, a change in points, or a relative change? Could a reader tell? What's the baseline?

11

Recap

Recap
  • Points subtract, percent divides. Say which you mean.
  • Odds aren't risks, and they drift apart when the outcome is common.
  • Give the baseline with any relative number, and use counts when your reader isn't a statistician.

Concepts in this lesson