One proportion: exact tests and honest intervals
Test a proportion against a target with the exact binomial or score test, and see why the textbook Wald interval is the one to avoid.
What runs in CodeSplash
- STAT054Exact binomial test Runs in CodeSplash
- STAT055One proportion score test Runs in CodeSplash
- One proportion (exact binomial / score test) Verified in Python and R
You will be able to
- Choose between an exact binomial test and a score test
- Explain why the Wald interval undercovers
- Report a proportion with a Wilson interval
Read first
A count out of a total
ReadIn mtcars, 13 of 32 cars have a manual transmission: a proportionProportion (bounded outcome)A value between 0 and 1 — a share, a rate or a probability. of 0.406. Is that compatible with an even split?
If each car is independently manual with probability , the count follows a binomial distribution. Each observation has to be a separate yes-or-no with the same chance; twenty passengers from one bus are not twenty independent observations.
Two tests
ReadThe exact binomial test adds up the binomial probabilities of every count at least as unusual as the one you saw. It needs no approximation.
The score test uses a normal approximation, with the spread taken from the null value:
Here the exact test gives p = .377 and the score test gives z = −1.06, p = .289. With small samples, exact tests are often conservative, because counts move in discrete jumps.
Guess the coverage
PredictPredict first
The usual textbook interval is . With and a true proportion of about one in ten, how often does a nominal 95% interval contain the truth?
Reveal
Well below 95%. The formula's standard error is computed at , and with it collapses to an interval of width zero. Try it in the next step.
Watch intervals fail
ExploreSlide the true proportion toward 0 or 1 and shrink . Compare how often the Wald, Wilson and Clopper–Pearson intervals capture the truth. Notice the coverage swinging as the true value moves.
EExplorable · Do proportion intervals keep their promise?
How often does a 95% interval for a proportion really contain the truth?
How often does the textbook Wald interval cover the truth here?
Confidence
Red: Wald. Blue: Wilson. The other: Clopper–Pearson, which never falls below the stated level and is often wider than needed. These are exact sums, not simulations.
Commit your prediction above to see the result
Make your prediction to see the result.
Pick an interval
Read| Interval | Character |
|---|---|
| Wilson score | Close to nominal; the recommended default |
| Clopper–Pearson | Exact, and conservative: never below nominal |
| Jeffreys | Close to nominal; has a Bayesian reading |
| Agresti–Coull | Simple and close to Wilson |
| Wald | Undercovers; avoid |
The mtcars Wilson interval runs from 0.26 to 0.58. It is wide, and an even split sits comfortably inside.
Read the result
Read13/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.
The exact R script · R 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)
))
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.
The exact Python script · Python 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 card reports the exact test, the Wilson interval and Cohen's = −0.19, a scale for the size of a gap between proportions.
With a large sample, small gaps become detectable: 1,755 of 4,526 applicants admitted, against a target of 35%, gives p < .001 and of only 0.08.
Mid-p and the continuity correction
ReadThe exact test is never too liberal, so at small n it is often too strict: its real error rate sits below α. Two options adjust this:
- Mid-p value (exact test) counts the observed outcome as half extreme. Its error rate is close to α on average, though no longer guaranteed below it.
- Continuity correction (score test) moves the count half a unit toward n·p0 before the z, as R's
prop.testdoes by default. It makes the score p slightly larger.
215/592 = .36, 95% CI [.33, .40], exact binomial test (mid-p) p < .001
- Proportion Blue
- 0.3632
- 95% CI (Wilson score)
- [0.3254, 0.4027]
- p (exact binomial test (mid-p))
- < .001
- z (score)
- 6.359
- p (exact)
- < .001
- p (score)
- < .001
Effect size
- Cohen's h 0.2464 · small
Plots
Wilson score interval; the line marks p0 = 0.25.
View data
| Proportion Blue | high | eye | low |
|---|---|---|---|
| 0.3632 | 0.4027 | Blue | 0.3254 |
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
| eye | n | Share |
|---|---|---|
| Brown | 220 | 0.3716 |
| Blue | 215 | 0.3632 |
| Hazel | 93 | 0.1571 |
| Green | 64 | 0.1081 |
- Event: eye = Blue (all other levels count as non-events); H0 proportion 0.25; alternative: two-sided.
The exact R script · R 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 bfef6eed9ff3a711
# Dataset: hair_eye (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/hair_eye.parquet", col_select = c("eye")))
n_input <- nrow(df)
df[["eye"]] <- factor(df[["eye"]], levels = c("Brown", "Blue", "Hazel", "Green")) # stored level order
df <- df[stats::complete.cases(df[c("eye")]), , 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("eye")) # 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 <- "eye"
levels_v <- c("Brown", "Blue", "Hazel", "Green") # stored level order
event <- "Blue"
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.25
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 (TRUE) {
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)
))
215/592 = .36, 95% CI [.33, .40], exact binomial test (mid-p) p < .001
- Proportion Blue
- 0.3632
- 95% CI (Wilson score)
- [0.3254, 0.4027]
- p (exact binomial test (mid-p))
- < .001
- z (score)
- 6.359
- p (exact)
- < .001
- p (score)
- < .001
Effect size
- Cohen's h 0.2464 · small
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
| eye | n | Share |
|---|---|---|
| Brown | 220 | 0.3716 |
| Blue | 215 | 0.3632 |
| Hazel | 93 | 0.1571 |
| Green | 64 | 0.1081 |
- Event: eye = Blue (all other levels count as non-events); H0 proportion 0.25; alternative: two-sided.
The exact Python script · Python 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 bfef6eed9ff3a711
# Dataset: hair_eye (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/hair_eye.parquet", columns=["eye"])
n_input = len(df)
df["eye"] = pd.Categorical(df["eye"], categories=["Brown", "Blue", "Hazel", "Green"]) # stored level order
df = df.dropna(subset=["eye"]) # listwise deletion over the analysis columns
df["eye"] = df["eye"].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, ["eye"]) # 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 = "eye"
levels = ["Brown", "Blue", "Hazel", "Green"] # stored level order
event = "Blue" 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.25
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 True:
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},
})
Check your understanding
CheckpointCheck yourself
For a score test of with , what is the standard error used in the denominator?
Show the answer
Answer: 0.05
√(0.5 × 0.5 / 100) = 0.05. The score test uses the null value, not the observed proportion.
Check yourself
You observe 0 events out of 25. What does the Wald 95% interval give?
Show the answer
Answer: a
The Wald standard error is zero when . Wilson or Clopper–Pearson give a useful upper limit.
Check yourself
Which breaks the binomial's assumptions?
Show the answer
Answer: b
Household members aren't independent. The effective sample size is smaller than 200, and the proportion's standard error is too small.
Check yourself
How does the mid-p value compare with the exact binomial p for the same data?
Show the answer
Answer: a
Mid-p subtracts half the probability of the observed outcome from the exact tail, so it is always a little smaller.
Do it in CodeSplash
In the appPick the Outcome, choose the Event level, and set the Reference proportion (p0). Test switches between exact and score, and Interval lists all the options above with Wilson as the default.
from scipy import stats
res = stats.binomtest(13, 32, p=0.5)
print(res.pvalue)
print(res.proportion_ci(confidence_level=0.95, method="wilson"))binom.test(13, 32, p = 0.5) # exact test, Clopper-Pearson interval
prop.test(13, 32, p = 0.5, correct = FALSE) # score test, Wilson intervalRecap
Recap- Use the exact binomial test for small samples; the score test agrees in larger ones.
- Report a Wilson interval. The Wald interval undercovers near 0 and 1.
- The binomial assumes independent observations, so check how the data were collected.
Concepts in this lesson