EProportions & counts · proportion.binomial
One proportion (exact binomial / score test)
Does the share of an outcome differ from a reference proportion?
Tests one proportion against p0 with the exact binomial test or the score z test, with a choice of interval (Wilson, Wilson with continuity correction, Clopper–Pearson, Jeffreys, Agresti–Coull, Wald) and Cohen's h.
A real result
Example “Boolean default event”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
13/32 = .41, 95% CI [.26, .58], exact binomial test p = .377
- Proportion true
- 0.4063
- 95% CI (Wilson score)
- [0.2552, 0.5774]
- p (exact binomial test)
- .377
- z (score)
- −1.061
- p (exact)
- .377
- p (score)
- .289
Effect size
- Cohen's h −0.1886 · negligible
Plots
Wilson score interval; the line marks p0 = 0.5.
View data
| Proportion true | high | manual | low |
|---|---|---|---|
| 0.4063 | 0.5774 | true | 0.2552 |
Assumptions
- Independent trials — Each row is one independent trial with the same probability.
- Large enough for the score test — The exact test needs no normal approximation.
Counts
| manual | n | Share |
|---|---|---|
| false | 19 | 0.5938 |
| true | 13 | 0.4063 |
- Event: manual = true (all other levels count as non-events); H0 proportion 0.5; alternative: two-sided.
13/32 = .41, 95% CI [.26, .58], exact binomial test p = .377
- Proportion true
- 0.4063
- 95% CI (Wilson score)
- [0.2552, 0.5774]
- p (exact binomial test)
- .377
- z (score)
- −1.061
- p (exact)
- .377
- p (score)
- .289
Effect size
- Cohen's h −0.1886 · negligible
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent trials — Each row is one independent trial with the same probability.
- Large enough for the score test — The exact test needs no normal approximation.
Counts
| manual | n | Share |
|---|---|---|
| false | 19 | 0.5938 |
| true | 13 | 0.4063 |
- Event: manual = true (all other levels count as non-events); H0 proportion 0.5; 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
- Boolean default eventmtcars · variable: manual
- Event greaterucb_admissions · variable: admit
- Multi level exact cihair_eye · variable: eye
- Score wilson ccapproval · variable: first
- Jeffreys small lesssymptoms · variable: after
- Exact midphair_eye · variable: eye
- Exact midp greaterucb_admissions · variable: admit
- Score continuityapproval · variable: first
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Categorical: counts, %, bar chart · Statistics Guide · A — Describe data
- One group vs a known proportion · Statistics Guide · E — Compare proportions / frequencies
- A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide
What you need
- Outcomecategorical / boolean · 1 column · 1–30 levels
- Each row is a trial; the chosen level is the event and every other level a non-event.
Choices you make
hypothesis
- Event leveldefault —
Level counted as a success; empty = the last stored level (true for true/false columns).
- Reference proportion (p0)default 0.5
The proportion under the null hypothesis, for example a target rate or a historical value.
- Alternative hypothesisdefault two-sided
Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.
- Proportion ≠ p0(default) — Tests for the proportion differing from p0 in either direction; keep it unless you fixed a direction before seeing the data.
- Proportion > p0 — Tests only for a proportion above p0; pick it only if you fixed this direction before seeing the data.
- Proportion < p0 — Tests only for a proportion below p0; pick it only if you fixed this direction before seeing the data.
- Testdefault exact
Exact binomial is always valid; the score z test is fine when n·p0 and n·(1 − p0) are at least 5.
- Exact binomial test(default) — Uses the binomial distribution directly; valid at any size, and the usual choice for small n.
- Score z test (n·p0 and n·(1 − p0) ≥ 5) — Uses the score z test; a good large-sample choice once n·p0 and n·(1 − p0) reach 5.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
- Mid-p valuedefault off
Counts the observed outcome as half extreme. The exact test is conservative at small n; mid-p is closer to the stated level, but no longer guaranteed below it.
- Continuity correctiondefault off
Applies Yates's correction to the score z test, as prop.test does by default; p-values become slightly larger.
statistics
- Intervaldefault wilson
Interval for the proportion. Wilson is the recommended default; Wald can be badly wrong near 0 or 1.
- Wilson score (recommended)(default) — Inverts the score test; good coverage at any sample size, so it's the usual choice.
- Wilson score with continuity correction — Wilson's interval with a continuity correction; wider, with coverage closer to the exact interval.
- Clopper–Pearson (exact) — Inverts the exact binomial test; guarantees at least the stated coverage, so it runs wide.
- Jeffreys — A Bayesian interval with a Jeffreys prior; coverage close to the stated level on average, and good at small n.
- Agresti–Coull — Adds about two successes and two failures to the Wald interval; easy to compute, and sound except at very small n.
- Wald (not recommended) — Estimate ± z·SE; coverage is poor at small n or extreme proportions, so use it only to match older work.
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.
Independent trials
Large enough for the score test
The score (normal) test needs n·p0 ≥ 5 and n·(1 − p0) ≥ 5; otherwise use the exact test.
- If violated → Exact binomial test — The exact test needs no normal approximation, so it is valid for any n and p0.
What it reports
- Tests: Proportion differs from p0
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n
- How many independent units the analysis used; it sets precision and power.
- proportion
- A value between 0 and 1 — a share, a rate or a probability.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- 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.
- p0
- A value between 0 and 1 — a share, a rate or a probability.
- z
- An estimate in standard-error units, compared with the standard normal distribution.
- p_exact
- How surprising your data would be if the null hypothesis were true, as a probability.
- p_score
- How surprising your data would be if the null hypothesis were true, as a probability.
- 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.
- ci_label
- A range of effect values compatible with your data at the chosen confidence level.
Per group, level or term: p_midp, z_cc, p_score_cc
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Intervals come from the codesplash twins (cs_prop_ci ≡ codesplash.stats.proportions.prop_ci); Clopper–Pearson and Jeffreys use Boost's (scipy) and R's beta quantiles (≈1e-12). The exact two-sided p uses the same 'minimum likelihood' rule with relative tolerance 1 + 1e-7.
The exact script CodeSplash ran for example “Boolean default event” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One proportion (exact binomial / score test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.binomial 1.2.0 · spec b4abe3ecd1bd6f47
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # intervals and the score test (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["manual"])
n_input = len(df)
df["manual"] = pd.Categorical(df["manual"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["manual"]) # listwise deletion over the analysis columns
df["manual"] = df["manual"].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, ["manual"]) # 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
v = "manual"
levels = ["false", "true"] # stored level order
event = "" or levels[-1] # default: the last level (for true/false columns, "true")
if event not in levels:
raise ValueError(f"{event!r} is not a level of {v}: {', '.join(levels)}")
k = int((df[v].astype(str) == event).sum())
n = len(df)
p0 = 0.5
alternative = "two-sided"
conf = 0.95
test = "exact" # "exact" binomial or "score" z
ci_method = "wilson"
p_exact = float(stats.binomtest(k, n, p=p0, alternative=alternative).pvalue) # exact binomial test
z, p_score = csp.score_test(k, n, p0, alternative) # score z (= prop.test(correct = FALSE))
p = p_exact if test == "exact" else p_score
ci_low, ci_high = csp.prop_ci(k, n, conf, ci_method)
phat = k / n
h = 2 * np.arcsin(np.sqrt(phat)) - 2 * np.arcsin(np.sqrt(p0)) # Cohen's h
test_label = "exact binomial test" if test == "exact" else "score z test"
# Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
from codesplash.stats import stat_options as csopt
extra = {}
if False:
extra["p_midp"] = csopt.binom_midp(k, n, p0, alternative)
if test == "exact":
p = extra["p_midp"]
test_label = "exact binomial test (mid-p)"
if False:
extra["z_cc"], extra["p_score_cc"] = csopt.score_test_cc(k, n, p0, alternative)
if test == "score":
p = extra["p_score_cc"]
test_label = "score z test with continuity correction"
ci_label = csp.CI_LABELS[ci_method]
# %% Assumptions
small = min(n * p0, n * (1 - p0))
assumptions = [{"key": "independence", "label": "Independent trials", "status": "info", "detail": "Each row is one independent trial with the same probability."}]
if test == "score":
assumptions.append({"key": "sample_size", "label": "Large enough for the score test", "status": "pass" if small >= 5 else "warn",
"detail": f"min(n·p0, n·(1 − p0)) = {small:.1f}" + (" (< 5): use the exact test." if small < 5 else ".")})
else:
assumptions.append({"key": "sample_size", "label": "Large enough for the score test", "status": "info", "detail": "The exact test needs no normal approximation."})
# %% Result
alpha = 1 - conf
size = magnitude(h, (0.2, 0.5, 0.8))
significance = (
f"The proportion differs significantly from {p0:g} ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with a proportion of {p0:g} ({cs.fmt_p(p)})."
)
summary = f"{k} of {n} rows ({phat:.1%}) have {v} = {event}; {conf:.0%} CI [{ci_low:.1%}, {ci_high:.1%}] ({ci_label}). {significance} Cohen's h = {h:.2f} ({size})."
cs.publish({
"method": "proportion.binomial",
"methodVersion": "1.2.0",
"title": "One proportion: " + test_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{k}/{n} = {cs.fmt_num(phat, leading_zero=False)}, {conf:.0%} CI [{cs.fmt_num(ci_low, leading_zero=False)}, {cs.fmt_num(ci_high, leading_zero=False)}], {test_label} {cs.fmt_p(p)}",
"statistics": [
{"key": "proportion", "label": f"Proportion {event}", "value": phat},
{"key": "ci", "label": f"{conf:.0%} CI ({ci_label})", "value": [ci_low, ci_high]},
{"key": "p", "label": f"p ({test_label})", "value": p, "format": "p"},
{"key": "z", "label": "z (score)", "value": z},
{"key": "p_exact", "label": "p (exact)", "value": p_exact, "format": "p"},
{"key": "p_score", "label": "p (score)", "value": p_score, "format": "p"},
],
"tables": [{
"key": "counts", "title": "Counts",
"columns": [{"key": "level", "label": v, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "share", "label": "Share", "type": "number"}],
"rows": [{"level": lv, "n": int((df[v].astype(str) == lv).sum()), "share": float((df[v].astype(str) == lv).mean())} for lv in levels],
}],
"effectSizes": [{"key": "cohens_h", "label": "Cohen's h", "value": float(h), "method": "2·asin√p̂ − 2·asin√p0", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {v} = {event} (all other levels count as non-events); H0 proportion {p0:g}; alternative: {alternative}."],
"charts": [cs.chart(
"proportion", "forest", f"Proportion {event}",
{"label": cs.col(v, [event]), "estimate": cs.col(f"Proportion {event}", [phat]),
"low": cs.col("low", [ci_low]), "high": cs.col("high", [ci_high])},
controls={"reference": p0}, note=f"{ci_label} interval; the line marks p0 = {p0:g}.",
)],
"values": {"k": k, "n": n, "proportion": phat, "p": p, "ci_low": ci_low, "ci_high": ci_high, "cohens_h": float(h), "p0": p0,
"z": z, "p_exact": p_exact, "p_score": p_score, "event": event, "test_label": test_label, "ci_label": ci_label, **extra},
})
The exact script CodeSplash ran for example “Boolean default event” · R version 4.5.1 (2025-06-13)
# One proportion (exact binomial / score test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.binomial 1.2.0 · spec b4abe3ecd1bd6f47
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_prop_ci, cs_score_test (twins of codesplash.stats.proportions)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("manual")))
n_input <- nrow(df)
df[["manual"]] <- factor(df[["manual"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("manual")]), , 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("manual")) # 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
v <- "manual"
levels_v <- c("false", "true") # stored level order
event <- ""
if (!nzchar(event)) event <- levels_v[length(levels_v)] # default: the last level (for true/false columns, "true")
if (!event %in% levels_v) stop(sprintf("'%s' is not a level of %s: %s", event, v, paste(levels_v, collapse = ", ")))
x <- as.character(df[[v]])
k <- sum(x == event)
n <- length(x)
p0 <- 0.5
alternative <- "two-sided"
conf <- 0.95
test <- "exact" # "exact" binomial or "score" z
ci_method <- "wilson"
p_exact <- binom.test(k, n, p = p0, alternative = sub("-", ".", alternative, fixed = TRUE))$p.value # exact binomial test
sc <- cs_score_test(k, n, p0, alternative) # score z (= prop.test(correct = FALSE))
z <- sc[1]
p_score <- sc[2]
p <- if (test == "exact") p_exact else p_score
ci <- cs_prop_ci(k, n, conf, ci_method)
phat <- k / n
h <- 2 * asin(sqrt(phat)) - 2 * asin(sqrt(p0)) # Cohen's h
test_label <- if (test == "exact") "exact binomial test" else "score z test"
# Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
extra <- list()
if (FALSE) {
extra$p_midp <- cs_binom_midp(k, n, p0, alternative)
if (test == "exact") {
p <- extra$p_midp
test_label <- "exact binomial test (mid-p)"
}
}
if (FALSE) {
scc <- cs_score_test_cc(k, n, p0, alternative)
extra$z_cc <- unname(scc[["z"]])
extra$p_score_cc <- unname(scc[["p"]])
if (test == "score") {
p <- extra$p_score_cc
test_label <- "score z test with continuity correction"
}
}
ci_label <- c(wilson = "Wilson score", "wilson-cc" = "Wilson score with continuity correction", "clopper-pearson" = "Clopper–Pearson (exact)",
jeffreys = "Jeffreys", "agresti-coull" = "Agresti–Coull", wald = "Wald")[[ci_method]]
# %% Assumptions
small <- min(n * p0, n * (1 - p0))
assumptions <- list(list(key = "independence", label = "Independent trials", status = "info", detail = "Each row is one independent trial with the same probability."))
assumptions[[2]] <- if (test == "score") {
list(key = "sample_size", label = "Large enough for the score test", status = if (small >= 5) "pass" else "warn",
detail = sprintf("min(n·p0, n·(1 − p0)) = %.1f%s", small, if (small < 5) " (< 5): use the exact test." else "."))
} else {
list(key = "sample_size", label = "Large enough for the score test", status = "info", detail = "The exact test needs no normal approximation.")
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(h, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
sprintf("The proportion differs significantly from %s (%s).", format(p0), cs_fmt_p(p))
} else {
sprintf("The data are compatible with a proportion of %s (%s).", format(p0), cs_fmt_p(p))
}
summary <- sprintf("%d of %d rows (%.1f%%) have %s = %s; %s CI [%.1f%%, %.1f%%] (%s). %s Cohen's h = %.2f (%s).",
k, n, phat * 100, v, event, pct, ci[1] * 100, ci[2] * 100, ci_label, significance, h, size)
cs_publish(list(
method = "proportion.binomial",
methodVersion = "1.2.0",
title = paste("One proportion:", test_label),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%d/%d = %s, %s CI [%s, %s], %s %s", k, n, cs_fmt_num(phat, leading_zero = FALSE), pct,
cs_fmt_num(ci[1], leading_zero = FALSE), cs_fmt_num(ci[2], leading_zero = FALSE), test_label, cs_fmt_p(p)),
statistics = list(
list(key = "proportion", label = paste("Proportion", event), value = phat),
list(key = "ci", label = sprintf("%s CI (%s)", pct, ci_label), value = c(ci[1], ci[2])),
list(key = "p", label = sprintf("p (%s)", test_label), value = p, format = "p"),
list(key = "z", label = "z (score)", value = z),
list(key = "p_exact", label = "p (exact)", value = p_exact, format = "p"),
list(key = "p_score", label = "p (score)", value = p_score, format = "p")
),
tables = list(list(
key = "counts", title = "Counts",
columns = list(list(key = "level", label = v, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "share", label = "Share", type = "number")),
rows = data.frame(level = levels_v, n = vapply(levels_v, function(lv) sum(x == lv), numeric(1)),
share = vapply(levels_v, function(lv) mean(x == lv), numeric(1)), row.names = NULL)
)),
effectSizes = list(list(key = "cohens_h", label = "Cohen's h", value = h, method = "2·asin√p̂ − 2·asin√p0", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s = %s (all other levels count as non-events); H0 proportion %s; alternative: %s.", v, event, format(p0), alternative)),
charts = list(cs_chart(
"proportion", "forest", paste("Proportion", event),
list(label = cs_col(v, event), estimate = cs_col(paste("Proportion", event), phat),
low = cs_col("low", ci[1]), high = cs_col("high", ci[2])),
controls = list(reference = p0), note = sprintf("%s interval; the line marks p0 = %s.", ci_label, format(p0))
)),
values = c(list(k = k, n = n, proportion = phat, p = p, ci_low = ci[1], ci_high = ci[2], cohens_h = h, p0 = p0,
z = z, p_exact = p_exact, p_score = p_score, event = event, test_label = test_label, ci_label = ci_label), extra)
))
Sources
- Wilson, E. B. (1927). Probable inference, the law of succession, and statistical inference. JASA, 22, 209–212.
- Newcombe, R. G. (1998). Two-sided confidence intervals for the single proportion. Statistics in Medicine, 17, 857–872.
- Brown, L. D., Cai, T. T., & DasGupta, A. (2001). Interval estimation for a binomial proportion. Statistical Science, 16, 101–133.
From the CodeSplash method registry · proportion.binomial v1.2.0.