Skip to content

Two proportions: z, Fisher, Barnard and Boschloo

Four tests compare two proportions. They differ in what they hold fixed, which is why Fisher's exact test can be more conservative than you need.

Applied ~11 min10 steps

What runs in CodeSplash

You will be able to

  • Run a two-proportion z test and connect it to chi-square
  • Explain what conditioning on the margins does to Fisher's test
  • Choose an unconditional exact test for small trials

Read first

01

The z test

Read

Pool the two groups to estimate the shared proportion under the null, then measure the gap in standard errors:

z=p^1−p^2pˉ(1−pˉ)(1/n1+1/n2)z = \frac{\hat p_1 - \hat p_2}{\sqrt{\bar p (1 - \bar p)(1/n_1 + 1/n_2)}}

Berkeley admissions in 1973: 1,198 of 2,691 men and 557 of 1,835 women were admitted, z = 9.60. Squaring z gives the chi-square statistic of the 2 × 2 table: 92.21. They are one test written two ways.

02

Small samples

Read

Seven of 12 treated patients responded, against 2 of 10 controls. The smallest expected count is about 4.1, so the normal approximation is on shaky ground.

Fisher's exact test fixes both margins of the table, and treats the remaining single cell as hypergeometric.

03

Enumerate the tables

Explore

Tea tasting is Fisher's own example. Fix the margins and list every possible table, each with its probability. Then watch how few distinct p-values there are, and what that does to the real error rate.

EExplorable · The lady tasting tea

With so few observations, how can you get a p-value without any approximation?

What is the one-sided p-value?

0.500
How sure?
4
4
0.01400.22910.51420.22930.0144

Colored bars are at least as good as what she scored: their total is the one-sided p-value.

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

Predict the ordering

Predict

Predict first

Fisher fixes both margins. Barnard and Boschloo fix only the group sizes, and search over the unknown common proportion. On the small trial, how does Fisher's p-value compare?

Fisher's p is the smallestFisher's p is the largestThey are all the same
Reveal

Largest. Fisher gives 0.099, Boschloo 0.083, Barnard 0.075, and the approximate z test 0.069.

05

Which exact test?

Read
TestFixesNote
FisherFisher's exact testFixes both margins of a 2 × 2 table and adds up hypergeometric probabilities of tables as extreme as yours.Both marginsConservative; standard when margins were truly fixed
BarnardBarnard's exact testAn exact test for two independent proportions that does not condition on the column totals, so it is usually more powerful than Fisher's.Group sizesUnconditional, using the z statistic
BoschlooBoschloo's testAn unconditional exact test that uses Fisher's p as its statistic, so it is never less powerful than Fisher.Group sizesUnconditional, using Fisher's p as its statistic; never worse than Fisher

Fisher's test isn't wrong for being conservative, but in a trial with fixed group sizes its error rate often sits well below 5%. Boschloo's test is uniformly more powerful, at a higher computing cost.

06

Read the result

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

Men were admitted at 0.445 and women at 0.304. The risk difference is 0.142 (95% CI 0.113 to 0.170).

Hold that thought: this overall gap is the start of a famous paradox, later in this track.

07

Barnard's two statistics

Read

Barnard's exact test ranks every possible table by a z statistic and adds up the probability of tables at least as extreme. The classic choice is the pooled z (one proportion for both groups in the standard error). The unpooled z uses each group's own proportion and can rank tables differently when the rates are far apart. Both are exact; pick one before looking.

Two independent proportionsRecorded · Python and R agreeRecorded 2026-11-21 · 43 values compared
R

Barnard's exact test (unpooled z), p = .023, RD = 0.300, 95% CI [0.049, 0.504]

p (Barnard's exact test (unpooled z))
.023
z
2.335
p (z test)
.020
p (Fisher's exact)
.037
p (Boschloo's exact)
.023
p (Barnard's exact)
.023

Effect size

  • Risk difference 0.3000 95% CI [0.0486, 0.5038]
  • Risk ratio 2 95% CI [1.076, 3.717]
  • Odds ratio 3.500 95% CI [1.201, 10.196]
  • Odds ratio (conditional MLE) 3.423 95% CI [1.067, 11.743]
  • Cohen's h 0.6129 · medium
  • Number needed to treat 3.333 95% CI [1.985, 20.584]

Plots

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

Wilson intervals; the line marks the pooled proportion.

View data
Proportion successhigharmlow
0.60000.7541treatment0.4232
0.30000.4788control0.1666

Assumptions

  • Expected counts ≥ 5 — Barnard's exact test (unpooled z) is exact, so expected counts do not matter (smallest 13.50).
  • Independent observations — Each row is a different subject in exactly one group.

Proportion with outcome = success

armEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
treatment18300.60000.42320.7541
control9300.30000.16660.4788
  • Event: outcome = success; differences are treatment − control; 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 28e36991a6c8b4db
# Dataset: e_guide_2x2 (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/e_guide_2x2.parquet", col_select = c("arm", "outcome")))
n_input <- nrow(df)
df[["arm"]] <- factor(df[["arm"]], levels = c("treatment", "control"))  # stored level order
df[["outcome"]] <- factor(df[["outcome"]], levels = c("failure", "success"))  # stored level order
df <- df[stats::complete.cases(df[c("arm", "outcome")]), , 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("arm", "outcome"))  # 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 <- "arm"
y <- "outcome"
groups <- levels(df[[g]])
if (length(groups) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(groups))
outcome_levels <- c("failure", "success")  # stored level order
event <- outcome_levels[length(outcome_levels)]  # 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 <- "barnard"
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 <- "unpooled"  # 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

Barnard's exact test (unpooled z), p = .023, RD = 0.300, 95% CI [0.049, 0.504]

p (Barnard's exact test (unpooled z))
.023
z
2.335
p (z test)
.020
p (Fisher's exact)
.037
p (Boschloo's exact)
.023
p (Barnard's exact)
.023

Effect size

  • Risk difference 0.3000 95% CI [0.0486, 0.5038]
  • Risk ratio 2 95% CI [1.076, 3.717]
  • Odds ratio 3.500 95% CI [1.201, 10.196]
  • Odds ratio (conditional MLE) 3.423 95% CI [1.067, 11.743]
  • Cohen's h 0.6129 · medium
  • Number needed to treat 3.333 95% CI [1.985, 20.584]

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

Assumptions

  • Expected counts ≥ 5 — Barnard's exact test (unpooled z) is exact, so expected counts do not matter (smallest 13.50).
  • Independent observations — Each row is a different subject in exactly one group.

Proportion with outcome = success

armEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
treatment18300.60000.42320.7541
control9300.30000.16660.4788
  • Event: outcome = success; differences are treatment − control; 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 28e36991a6c8b4db
# Dataset: e_guide_2x2 (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/e_guide_2x2.parquet", columns=["arm", "outcome"])
n_input = len(df)
df["arm"] = pd.Categorical(df["arm"], categories=["treatment", "control"])  # stored level order
df["outcome"] = pd.Categorical(df["outcome"], categories=["failure", "success"])  # stored level order
df = df.dropna(subset=["arm", "outcome"])  # listwise deletion over the analysis columns
df["arm"] = df["arm"].cat.remove_unused_categories()
df["outcome"] = df["outcome"].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, ["arm", "outcome"])  # 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 = "arm", "outcome"
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 = ["failure", "success"]  # stored level order
event = outcome_levels[-1]  # 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 = "barnard"
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 = "unpooled"  # 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,
    },
})
08

Check your understanding

Checkpoint

Check yourself

A two-proportion z test gives z = 2. What is the chi-square statistic for the same 2 × 2 table, without continuity correction?

Show the answer

Answer: 4

χ² = z² = 4.

Check yourself

A small trial has fixed group sizes of 15 and 15. Which test gives the most power while controlling the error rate exactly?

Show the answer

Answer: a

The z test's error rate is only approximately controlled at this size. Fisher controls it exactly but is conservative. Boschloo controls it exactly and is at least as powerful.

Check yourself

Why does the z test pool the two groups in its standard error?

Show the answer

Answer: a

The test is calculated under the null. The confidence interval for the difference doesn't assume equal proportions, which is why test and interval can occasionally disagree.

Check yourself

You ran Barnard's test with the pooled z, then switched to the unpooled z because its p-value was smaller. What's the problem?

Show the answer

Answer: b

Both statistics give exact tests. Picking whichever gives the smaller p after looking turns two valid tests into one invalid one.

09

Do it in CodeSplash

In the app

Choose Groups, Outcome and Event level. Test offers the z test, Fisher, Boschloo and Barnard. For small tables the card reports the others' p-values too, so you can see how much the choice matters. Pick it in advance.

Python
from scipy import stats
from statsmodels.stats.proportion import proportions_ztest

print(proportions_ztest([7, 2], [12, 10]))

table = [[7, 5], [2, 8]]
print(stats.fisher_exact(table))
print(stats.barnard_exact(table))
print(stats.boschloo_exact(table))
R
prop.test(c(7, 2), c(12, 10), correct = FALSE)

table <- matrix(c(7, 5, 2, 8), nrow = 2, byrow = TRUE)
fisher.test(table)
# install.packages("Exact")
Exact::exact.test(table, method = "boschloo", to.plot = FALSE)
10

Recap

Recap
  • The z test and the 2 × 2 chi-square are the same test.
  • Fisher conditions on both margins, so it's conservative when only group sizes were fixed.
  • Barnard and Boschloo are unconditional exact tests, and worth using for small trials.

Concepts in this lesson