Skip to content

EProportions & counts · proportion.two_sample

Two independent proportions (z, Fisher, Boschloo, Barnard, non-inferiority)

Does the share of an outcome differ between two independent groups?

Compares the proportion of an event between two groups with the pooled two-proportion z test, Fisher's exact test or Boschloo's unconditional exact test, and reports the risk difference (Newcombe interval), risk ratio (Katz), odds ratio (Woolf and conditional MLE), NNT and Cohen's h. Barnard's unconditional exact test is also available, and the comparison can be framed as non-inferiority or equivalence with Farrington–Manning score tests at a margin on the difference or ratio scale.

Verified in Python and R Python and R agree to 6 decimals Also called Barnard's test, Barnard unconditional exact test, Farrington–Manning test…

A real result

Example “Z default”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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.
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.

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

Worked examples in the app

  • Z defaultucb_admissions · group: gender · outcome: admit
  • Small boschloosmall_trial · group: arm · outcome: response
  • Fisher greater correctedsmall_trial · group: arm · outcome: response
  • Boolean groups zero cellrapid_test · group: rapid test · outcome: culture
  • Barnard guidee_guide_2x2 · group: arm · outcome: outcome
  • Barnard unpoolede_guide_2x2 · group: arm · outcome: outcome
  • Barnard unpooled greatere_guide_2x2 · group: arm · outcome: outcome
  • Barnard small greatersmall_trial · group: arm · outcome: response

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Two groups, binary outcome: two-proportion z, Fisher's exact · Statistics Guide · B — Compare groups
  • Two independent proportions · Statistics Guide · E — Compare proportions / frequencies
  • Expected counts ≥ 5? otherwise exact tests · Statistics Guide · E — Compare proportions / frequencies
  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide

What you need

Groupscategorical / boolean · 1 column · 2–2 levels
Exactly two groups. Differences are first group − second group (stored level order).
Outcomecategorical / boolean · 1 column · 2–30 levels
The event level counts as a success; every other level is a non-event.

Choices you make

hypothesis

Event leveldefault —

The outcome level counted as the event (default the last stored level — true for true/false columns).

Testdefault z

The primary test. All are reported; the unconditional exact tests (Boschloo, Barnard) are more powerful than Fisher's and are computed for up to 1,000 rows.

  • Two-proportion z test (pooled)(default) — The pooled large-sample test; the usual choice when every cell has enough counts.
  • Fisher's exact test — Conditions on both margins; exact for small samples, but conservative.
  • Boschloo's exact test (unconditional) — An exact test that doesn't condition on the margins; more powerful than Fisher's, and slower.
  • Barnard's exact test (unconditional) — Unconditional exact test with the pooled z statistic, maximized over the common proportion.
Barnard statisticdefault pooled

The statistic Barnard's exact test orders tables by. Both are exact; they rank tables differently and can give different p-values.

  • Pooled z (default)(default) — Uses the z statistic with the pooled proportion, as in Barnard's and Suissa–Shuster's tests.
  • Unpooled z — Uses each group's own proportion in the standard error; can be more powerful when the groups' rates differ a lot.
Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Proportions differ (≠)(default) — Tests for a difference in proportions in either direction; keep it unless you fixed a direction before seeing the data.
  • First group higher (>) — Tests only for the first group being higher; pick it only if you fixed this direction before seeing the data.
  • First group lower (<) — Tests only for the first group being lower; pick it only if you fixed this direction before seeing the data.
Hypothesisdefault superiority

Non-inferiority and equivalence need a margin chosen before seeing the data (record why in the analysis notes).

  • Difference (superiority)(default) — Is there any difference between the groups?
  • Non-inferiority — Is the first group no worse than the second by more than the margin? One Farrington–Manning score test.
  • Equivalence — Is the difference within ± the margin? Two one-sided Farrington–Manning tests; p is the larger.
Margin on thedefault difference

Whether the non-inferiority or equivalence margin is a risk difference or a risk ratio.

  • Risk difference(default) — Sets the margin as a gap between proportions; the usual choice and the easiest to explain.
  • Risk ratio — Sets the margin as a ratio of proportions; pick it when the acceptable loss scales with the baseline rate.
Margin (difference)default 0.1

The largest difference in proportions that still counts as no worse / equivalent, e.g. 0.1 = 10 percentage points.

Margin (ratio)default 0.8

A risk ratio such as 0.8; equivalence uses 0.8 to 1/0.8 = 1.25.

Better outcome isdefault higher

Which direction is better for the outcome, so the margin is applied to the right side.

  • Higher (first group must not be lower by more than the margin)(default) — Use when a higher proportion is better, such as a cure rate; the first group may fall short by at most the margin.
  • Lower (first group must not be higher by more than the margin) — Use when a lower proportion is better, such as a failure rate; the first group may run over by at most the margin.
Confidence leveldefault 0.95

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

options

Continuity correction (z test)default off

Yates' correction (capped at |Δ| / Σ 1/n, as R's prop.test). Off by default; it makes the z test conservative.

Checks and remedies

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

  • Expected counts ≥ 5

    The z test needs every expected count (n × pooled proportion) of at least 5; otherwise use an exact test.

    • If violated → Fisher's exact test — Exact under the null hypothesis whatever the counts, so small expected counts do not distort the p-value.
  • Independent observations

    Each subject appears once, in one group; use McNemar's test for paired yes/no data.

What it reports

  • Tests: Difference in proportions (or non-inferiority / equivalence, as set)
n
How many independent units the analysis used; it sets precision and power.
n_1
How many independent units the analysis used; it sets precision and power.
n_2
How many independent units the analysis used; it sets precision and power.
x_1
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
x_2
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
p_1
A value between 0 and 1 — a share, a rate or a probability.
p_2
A value between 0 and 1 — a share, a rate or a probability.
risk_diff
The difference in event probabilities between groups; the number that matters for decisions.
rd_ci_low
A range of effect values compatible with your data at the chosen confidence level.
rd_ci_high
A range of effect values compatible with your data at the chosen confidence level.
z
An estimate in standard-error units, compared with the standard normal distribution.
chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
p_z
An estimate in standard-error units, compared with the standard normal distribution.
fisher_p
How surprising your data would be if the null hypothesis were true, as a probability.
cond_or
How many times higher the odds of an event are in one group than another; 1 means no difference.
cond_or_ci_low
A range of effect values compatible with your data at the chosen confidence level.
cond_or_ci_high
A range of effect values compatible with your data at the chosen confidence level.
boschloo_p
How surprising your data would be if the null hypothesis were true, as a probability.
barnard_p
An exact test for two independent proportions that does not condition on the column totals, so it is usually more powerful than Fisher's.
barnard_z
An estimate in standard-error units, compared with the standard normal distribution.
fm_z_low
Score test that two proportions differ by a stated amount or ratio, with variance estimated at that null; used for non-inferiority.
fm_p_low
Score test that two proportions differ by a stated amount or ratio, with variance estimated at that null; used for non-inferiority.
fm_z_high
A range of effect values compatible with your data at the chosen confidence level.
fm_p_high
Score test that two proportions differ by a stated amount or ratio, with variance estimated at that null; used for non-inferiority.
margin_low
A range of effect values compatible with your data at the chosen confidence level.
margin_high
A range of effect values compatible with your data at the chosen confidence level.
p
How surprising your data would be if the null hypothesis were true, as a probability.
odds_ratio
How many times higher the odds of an event are in one group than another; 1 means no difference.
or_ci_low
A range of effect values compatible with your data at the chosen confidence level.
or_ci_high
A range of effect values compatible with your data at the chosen confidence level.
risk_ratio
The probability of the event in one group divided by that in another.
rr_ci_low
A range of effect values compatible with your data at the chosen confidence level.
rr_ci_high
A range of effect values compatible with your data at the chosen confidence level.
nnt
How many people must receive the treatment for one extra to benefit; 1 divided by the risk difference.
nnt_ci_low
A range of effect values compatible with your data at the chosen confidence level.
nnt_ci_high
A range of effect values compatible with your data at the chosen confidence level.
cohens_h
The gap between two proportions on the arcsine scale, so equal values of h are about equally hard to detect.
min_expected
The counts a contingency table would have if the variables were independent; χ² needs them not too small.
level_1
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
level_2
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
event
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
test_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.

Per group, level or term: barnard_statistic

Python and R

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

Default traps between the two languages

  • The conditional-MLE odds ratio and its interval come from root finding: scipy's odds_ratio in Python, cs_fisher_or solved to 1e-12 in R. stats::fisher.test stops much earlier (about 1e-4), so it can differ from these: median 1.7e-5 relative on the odds ratio and 6e-5 on a limit across 400 tables, and much more on extreme tables, where it is the inaccurate side. On (2, 1500, 1500, 5) it reports 0, and the true root is 5.1148e-6.
  • Boschloo's test is the codesplash twin in both engines (grid of 1,000 nuisance values + golden-section search); it matches scipy.stats.boschloo_exact to ≈1e-13.
  • Barnard's test (cs_barnard ≡ csx.barnard) counts tables whose z ties the observed one (within 1e-7) as at least as extreme and matches R's Exact::exact.test(method = 'z-pooled') to ≈1e-11. scipy.stats.barnard_exact compares floating-point statistics strictly, so exactly tied tables can drop out of its tail: on the guide's example (18/30 vs 9/30) scipy gives p = 0.02276 and the exact definition 0.02293.
  • The Farrington–Manning difference test uses the closed-form constrained MLE (the true maximum); statsmodels' test_proportions_2indep(method = 'score', compare = 'diff') uses a different restricted estimate (z = 1.5677 vs 1.5656 at δ0 = 0.1 on the guide's example). The ratio form matches statsmodels exactly.
Python

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

The exact script CodeSplash ran for example “Z default” · 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())
))

Sources

  • Newcombe, R. G. (1998). Interval estimation for the difference between independent proportions: comparison of eleven methods. Statistics in Medicine, 17, 873–890.
  • Katz, D., Baptista, J., Azen, S. P., & Pike, M. C. (1978). Obtaining confidence intervals for the risk ratio in cohort studies. Biometrics, 34, 469–474.
  • Barnard, G. A. (1947). Significance tests for 2 × 2 tables. Biometrika, 34, 123–138.
  • Suissa, S., & Shuster, J. J. (1985). Exact unconditional sample sizes for the 2 × 2 binomial trial. JRSS A, 148, 317–327.
  • Farrington, C. P., & Manning, G. (1990). Test statistics and sample size formulae for comparative binomial trials with null hypothesis of non-zero risk difference or non-unity relative risk. Statistics in Medicine, 9, 1447–1454.
  • Boschloo, R. D. (1970). Raised conditional level of significance for the 2 × 2-table when testing the equality of two probabilities. Statistica Neerlandica, 24, 1–9.
  • Altman, D. G. (1998). Confidence intervals for the number needed to treat. BMJ, 317, 1309–1312.

From the CodeSplash method registry · proportion.two_sample v1.2.0.