Skip to content

Risk difference, risk ratio or odds ratio?

One 2 × 2 table gives three effect sizes that can tell very different stories. Learn to convert them, and which to report.

Introductory ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Compute RD, RR, OR and NNT from a 2 × 2 table
  • Explain why an odds ratio overstates a risk ratio when events are common
  • Choose a measure suited to your design and your audience

Read first

01

One table, three numbers

Read
EventNo eventTotal
Group 1aabbn1n_1
Group 2ccddn2n_2
RD=an1−cn2RR=a/n1c/n2OR=a db c\mathrm{RD} = \frac{a}{n_1} - \frac{c}{n_2} \qquad \mathrm{RR} = \frac{a / n_1}{c / n_2} \qquad \mathrm{OR} = \frac{a\, d}{b\, c}

The 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/∣RD∣1 / |\mathrm{RD}|: how many people you'd treat for one extra event.

02

Work one through

Predict

Predict first

A trial has responses in 18 of 30 treated patients and 9 of 30 controls. Responses are common.

How do the odds ratio and the risk ratio compare?

The odds ratio is larger than the risk ratioThe risk ratio is larger than the odds ratioThey are about equal
Reveal

The odds ratio is larger: 3.50 against a risk ratio of 2.00. The risk difference is 0.30, so about 3.3 patients per extra response.

03

Translate them

Explore

Change the baseline risk with the odds ratio fixed, and watch the risk ratio and risk difference move. At very low baseline risks, the OR and RR almost agree. At high ones they drift far apart.

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.

04

Read the card

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

For the Berkeley admissions: RD = 0.142, RR = 1.47 (95% CI 1.35 to 1.59), OR = 1.84 (95% CI 1.62 to 2.09).

Same data. "Nearly twice the odds" sounds larger than "a 14-point gap", so choosing the measure is also choosing the headline.

05

Which one?

Reflect
You wantUse
Absolute impact on peopleRisk difference, NNT
A readable relative effectRisk ratio
A case-control design, or logistic regressionOdds ratio

In a case-control study you chose how many cases to sample, so risks can't be estimated, but the OR still can. In most other settings, report an absolute measure together with a relative one.

Which pair would you use to tell a colleague outside statistics about your last result?

06

Check your understanding

Checkpoint

Check yourself

Events occur in 20 of 100 treated and 10 of 100 controls. What is the risk ratio?

Show the answer

Answer: 2

0.20 / 0.10 = 2.

Check yourself

Same table: 20 of 100 treated, 10 of 100 controls. What is the odds ratio? Two decimals.

Show the answer

Answer: 2.25

(20 × 90) / (80 × 10) = 1800 / 800 = 2.25. It's larger than the risk ratio because events aren't rare.

Check yourself

You sampled 100 cases and 100 controls, then looked back at exposure. Which measure is valid?

Show the answer

Answer: c

You set the ratio of cases to controls by design, so event risks in the sample aren't real risks. The odds ratio stays valid under this sampling.

Check yourself

A treatment reduces risk from 15% to 10%. What is the number needed to treat?

Show the answer

Answer: 20

The risk difference is 0.05, and 1 / 0.05 = 20.

07

Do it in CodeSplash

In the app

Every two-proportion card lists all these measures with intervals, and the sentence names the risk difference, risk ratio and odds ratio together. For adjusted odds ratios, use logistic regression in the Regression track.

Python
import numpy as np
from statsmodels.stats.contingency_tables import Table2x2

t = Table2x2(np.array([[18, 12], [9, 21]]))
print("RD", 18 / 30 - 9 / 30)
print("RR", t.riskratio, t.riskratio_confint())
print("OR", t.oddsratio, t.oddsratio_confint())
R
a <- 18; b <- 12; c <- 9; d <- 21
c(RD = a / (a + b) - c / (c + d),
  RR = (a / (a + b)) / (c / (c + d)),
  OR = (a * d) / (b * c))
08

Recap

Recap
  • RD is absolute, RR is relative, and OR is the ratio of odds.
  • OR and RR are close only when events are rare; with common events, OR looks bigger.
  • Report absolute and relative effects together, and pick the measure your design allows.

Concepts in this lesson