Counts over time: exact Poisson tests and the E-test
Events per patient day or per thousand hours need exposure in the denominator. Test one rate exactly, compare two by conditioning, or use the unconditional E-test.
What runs in CodeSplash
- STAT074One sample exact Poisson test Runs in CodeSplash
- STAT075Two sample exact Poisson rate test Runs in CodeSplash
- STAT076Poisson E test Runs in CodeSplash
- Poisson rates (one rate or two rates compared) Verified in Python and R
You will be able to
- Compute a rate from events and exposure
- Compare two rates with the exact conditional test, using its link to the binomial
- Say when the E-test differs from the exact test, and when overdispersion breaks both
Events per unit of exposure
ReadA ward counts infections over patient days. A count on its own says little, because watching for longer gives more events. Divide by the exposureExposureHow much opportunity each row had to produce the count (policy-years, hours, area), so the model learns a rate. to get a rate:
The PoissonPoisson distributionThe count of independent events at a steady rate, with a variance equal to its mean. model fits events that happen independently at a constant rate. Exposure can be any measure of opportunity: person-years, machine hours or kilometers of pipe.
Predict one rate
PredictPredict first
You see 12 events over 100 units of exposure. The target is 8 per 100, so you expected 8 events. What p-value do you expect for the two-sided exact test?
Make your guess between 0 and 1 p-value, then reveal.
Reveal
p = .154. The observed rate is 12 per 100, with an exact 95% CI from 6.2 to 21.0. Few events give a wide interval, and the target sits inside it.
Two rates, one binomial
ReadIf two rates are equal, the way the total events split between the groups depends only on the exposures:
Here is the null rate ratio. Conditioning removes the unknown common rate, which is why this test is exact.
Treated units had 12 events over 100; controls had 7 over 90. Under equal rates, each of the 19 events lands in the treated group with chance . The rate ratio is 1.54 (95% CI 0.56 to 4.63), p = .492.
Exact or E-test?
PredictPredict first
The E-testPoisson E-testAn unconditional test comparing two Poisson rates; more powerful than the conditional (binomial) test when events are few. doesn't condition on the total. It compares the rate difference with its standard error, then adds up the probabilities of all outcomes at least as extreme, at estimated null rates. With only 19 events, how does its p-value compare with the exact test's?
Reveal
Smaller: p = .362 against p = .492. Conditional tests move in discrete steps and are conservative with few events. The E-test tends to have more power there, and both still leave these data compatible with equal rates.
The estimated null rates are rates, so each group's Poisson probabilities use its exposure times its rate as the expected count:
where holds the outcomes whose standardized difference is at least as extreme as the observed one.
Read the result
ReadIRR = 0.56, 95% CI [0.39, 0.80], p < .001
- p (exact conditional test)
- < .001
- p (exact conditional)
- < .001
- E-test statistic
- −3.353
- p (E-test)
- < .001
Effect size
- Rate ratio (treatment / control) 0.5608 95% CI [0.3900, 0.7987]
- Rate difference per 1000.00 −6.283 95% CI [−9.956, −2.611]
Plots
Exact (Garwood) intervals.
View data
| Rate per 1000.00 | high | group | low |
|---|---|---|---|
| 14.306 | 17.565 | control | 11.518 |
| 8.023 | 10.548 | treatment | 5.973 |
Assumptions
- Events occur independently at a constant rate — Exact Poisson tests assume no clustering; overdispersed counts make them anti-conservative (consider count regression).
- Valid counts and exposure — Events are whole numbers ≥ 0 and exposure is > 0 on every row.
Rates per 1000.00 units of exposure
| Group | Events | Exposure | Rate | Lower (exact) | Upper (exact) |
|---|---|---|---|---|---|
| control | 91 | 6,361 | 14.306 | 11.518 | 17.565 |
| treatment | 51 | 6,357 | 8.023 | 5.973 | 10.548 |
- The exact conditional test is of the rate ratio = 1.00; the E-test is of the rate difference = 0.00 per 1000.00.
The exact R script · R R version 4.5.1 (2025-06-13)
# Poisson rates (one rate or two rates compared)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method rates.poisson 1.2.1 · spec 582eec271dbe7f63
# Dataset: s4_rates (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_cnt_etest (port of scipy.stats.poisson_means_test), cs_cnt_garwood, cs_lens
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_rates.parquet", col_select = c("infections", "patient days", "arm")))
n_input <- nrow(df)
df[["arm"]] <- factor(df[["arm"]], levels = c("control", "treatment")) # stored level order
df <- df[stats::complete.cases(df[c("infections", "patient days", "arm")]), , 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("infections", "patient days", "arm")) # infinite values stop the run (registry/errors.yaml)
# %% Data checks
ev <- "infections"
ex <- "patient days"
events <- as.numeric(df[[ev]])
exposure <- as.numeric(df[[ex]])
bad_counts <- sum(events < 0 | events != round(events))
if (bad_counts > 0) cs_error("CS_E_INVALID_VALUES", column = ev, requirement = "whole numbers ≥ 0 (event counts)", count = bad_counts)
if (any(exposure <= 0)) cs_error("CS_E_INVALID_VALUES", column = ex, requirement = "above 0 on every row (time at risk or size)", count = sum(exposure <= 0))
n <- nrow(df)
per <- 1000 # display scale: rates per this many units of exposure
alternative <- "two-sided"
conf <- 0.95
z <- stats::qnorm(1 - (1 - conf) / 2)
X <- sum(events)
T <- sum(exposure)
values <- list(n = n, events_total = X, exposure_total = T, per = per)
notes <- list()
# %% Two rates: exact conditional test of the rate ratio
g <- "arm"
lvls <- levels(df[[g]])
if (length(lvls) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(lvls))
reference <- lvls[1] # denominator of the rate ratio
if (!reference %in% lvls) cs_error("CS_E_NOT_A_LEVEL", level = reference, column = g)
comparison <- if (reference == lvls[1]) lvls[2] else lvls[1]
grp <- as.character(df[[g]])
xc <- sum(events[grp == comparison]); tc <- sum(exposure[grp == comparison])
xr <- sum(events[grp == reference]); tr <- sum(exposure[grp == reference])
ratio0 <- 1
pt <- stats::poisson.test(c(xc, xr), c(tc, tr), r = ratio0, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)
ratio <- unname(pt$estimate)
ci <- as.numeric(pt$conf.int)
p_exact <- pt$p.value
test <- "exact"
diff0 <- 0 # null rate difference on the display scale (per the units above)
et <- cs_cnt_etest(xc, tc, xr, tr, diff = diff0 / per, alternative = alternative) # E-test of the rate difference
z_etest <- unname(et[1])
p_etest <- unname(et[2])
p <- if (test == "etest") p_etest else p_exact
test_label <- if (test == "etest") "E-test" else "exact conditional test"
diff <- (xc / tc - xr / tr) * per
se_diff <- sqrt(xc / tc^2 + xr / tr^2) * per
wald <- if (xc > 0 && xr > 0) {
se_log <- sqrt(1 / xc + 1 / xr)
c(ratio * exp(-z * se_log), ratio * exp(z * se_log))
} else c(NaN, NaN)
rows <- list()
for (lv in c(reference, comparison)) {
x_ <- if (lv == reference) xr else xc
t_ <- if (lv == reference) tr else tc
ci_g <- cs_cnt_garwood(x_, conf)
rows[[length(rows) + 1]] <- list(group = lv, events = x_, exposure = t_, rate = x_ / t_ * per, low = ci_g[1] / t_ * per, high = ci_g[2] / t_ * per)
values[[sprintf("events[%s]", lv)]] <- x_
values[[sprintf("exposure[%s]", lv)]] <- t_
values[[sprintf("rate[%s]", lv)]] <- x_ / t_ * per
values[[sprintf("rate_low[%s]", lv)]] <- ci_g[1] / t_ * per
values[[sprintf("rate_high[%s]", lv)]] <- ci_g[2] / t_ * per
}
values <- c(values, list(
mode = "two-sample", reference = reference, comparison = comparison, p = p, p_exact = p_exact, test_label = test_label, diff0 = diff0,
estimate = ratio,
ci_low = ci[1], ci_high = ci[2], ratio = ratio, ratio_ci_low = ci[1], ratio_ci_high = ci[2],
p_etest = p_etest, z_etest = z_etest, diff = diff, diff_ci_low = diff - z * se_diff, diff_ci_high = diff + z * se_diff,
ratio_wald_low = wald[1], ratio_wald_high = wald[2], rate_comp = xc / tc * per, rate_ref = xr / tr * per
))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("Rate ratio %s / %s = %s, %s CI [%s, %s], exact conditional test %s (E-test %s).",
comparison, reference, cs_fmt_num(ratio), pct, cs_fmt_num(ci[1]), cs_fmt_num(ci[2]), cs_fmt_p(p_exact), cs_fmt_p(p_etest))
apa <- if (test == "etest") {
sprintf("E-test z = %s, %s, rate difference = %s per %s, %s CI [%s, %s]", cs_fmt_num(z_etest), cs_fmt_p(p), cs_fmt_num(diff), cs_fmt_num(per), pct,
cs_fmt_num(diff - z * se_diff), cs_fmt_num(diff + z * se_diff))
} else {
sprintf("IRR = %s, %s CI [%s, %s], %s", cs_fmt_num(ratio), pct, cs_fmt_num(ci[1]), cs_fmt_num(ci[2]), cs_fmt_p(p))
}
notes <- c(notes, sprintf("The exact conditional test is of the rate ratio = %s; the E-test is of the rate difference = %s per %s.",
cs_fmt_num(ratio0), cs_fmt_num(diff0), cs_fmt_num(per)))
statistics <- list(
list(key = "p", label = sprintf("p (%s)", test_label), value = p, format = "p"),
list(key = "p_exact", label = "p (exact conditional)", value = p_exact, format = "p"),
list(key = "z_etest", label = "E-test statistic", value = z_etest),
list(key = "p_etest", label = "p (E-test)", value = p_etest, format = "p")
)
effects <- list(
list(key = "ratio", label = sprintf("Rate ratio (%s / %s)", comparison, reference), value = ratio, ciLow = ci[1], ciHigh = ci[2],
ciLevel = conf, method = "exact (conditional binomial)"),
list(key = "diff", label = sprintf("Rate difference per %s", cs_fmt_num(per)), value = diff, ciLow = diff - z * se_diff, ciHigh = diff + z * se_diff,
ciLevel = conf, method = "Wald")
)
# Lens on the rate ratio (equivalence / non-inferiority): log rate ratio with its Wald SE, normal
# reference, bounds entered as rate ratios and tested on the log scale (stream A's lens twin)
lens_kind <- "none"
if (lens_kind != "none") {
lens_low <- NULL
lens_high <- NULL
if ((!is.null(lens_low) && lens_low <= 0) || (!is.null(lens_high) && lens_high <= 0)) stop("Lens bounds are rate ratios and must be positive (e.g. 0.8 and 1.25).")
if (xc == 0 || xr == 0) {
warnings <- c(warnings, "A group has no events, so the log rate ratio is undefined and the lens is not computed.")
} else {
lens <- cs_lens(lens_kind, log(ratio), sqrt(1 / xc + 1 / xr), NULL,
if (is.null(lens_low)) NULL else log(lens_low), if (is.null(lens_high)) NULL else log(lens_high), 1 - conf)
lens$lens_ci_low <- exp(lens$lens_ci_low) # back to the ratio scale
lens$lens_ci_high <- exp(lens$lens_ci_high)
values <- c(values, lens)
summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
statistics <- c(statistics, list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")))
notes <- c(notes, sprintf("The lens interval [%.3g, %.3g] is the %.0f%% Wald interval for the rate ratio.", lens$lens_ci_low, lens$lens_ci_high,
(1 - 2 * (1 - conf)) * 100))
}
}
# %% Assumptions
assumptions <- list(
list(key = "poisson", label = "Events occur independently at a constant rate", status = "info",
detail = "Exact Poisson tests assume no clustering; overdispersed counts make them anti-conservative (consider count regression)."),
list(key = "counts", label = "Valid counts and exposure", status = "pass", detail = "Events are whole numbers ≥ 0 and exposure is > 0 on every row.")
)
# %% Result
cs_publish(list(
method = "rates.poisson",
methodVersion = "1.2.1",
title = "Poisson rates",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = statistics,
tables = list(list(
key = "rates", title = sprintf("Rates per %s units of exposure", cs_fmt_num(per)),
columns = list(list(key = "group", label = "Group", type = "string"), list(key = "events", label = "Events", type = "integer"),
list(key = "exposure", label = "Exposure", type = "number"), list(key = "rate", label = "Rate", type = "number"),
list(key = "low", label = "Lower (exact)", type = "number"), list(key = "high", label = "Upper (exact)", type = "number")),
rows = rows
)),
effectSizes = effects,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = list(cs_chart(
"rates", "forest", sprintf("Rate per %s", cs_fmt_num(per)),
list(label = cs_col("group", vapply(rows, function(r) r$group, "")), estimate = cs_col(sprintf("Rate per %s", cs_fmt_num(per)), vapply(rows, function(r) r$rate, 0)),
low = cs_col("low", vapply(rows, function(r) r$low, 0)), high = cs_col("high", vapply(rows, function(r) r$high, 0))),
note = "Exact (Garwood) intervals."
)),
values = values
))
IRR = 0.56, 95% CI [0.39, 0.80], p < .001
- p (exact conditional test)
- < .001
- p (exact conditional)
- < .001
- E-test statistic
- −3.353
- p (E-test)
- < .001
Effect size
- Rate ratio (treatment / control) 0.5608 95% CI [0.3900, 0.7987]
- Rate difference per 1000.00 −6.283 95% CI [−9.956, −2.611]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Events occur independently at a constant rate — Exact Poisson tests assume no clustering; overdispersed counts make them anti-conservative (consider count regression).
- Valid counts and exposure — Events are whole numbers ≥ 0 and exposure is > 0 on every row.
Rates per 1000.00 units of exposure
| Group | Events | Exposure | Rate | Lower (exact) | Upper (exact) |
|---|---|---|---|---|---|
| control | 91 | 6,361 | 14.306 | 11.518 | 17.565 |
| treatment | 51 | 6,357 | 8.023 | 5.973 | 10.548 |
- The exact conditional test is of the rate ratio = 1.00; the E-test is of the rate difference = 0.00 per 1000.00.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Poisson rates (one rate or two rates compared)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method rates.poisson 1.2.1 · spec 582eec271dbe7f63
# Dataset: s4_rates (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 counts as csc # exact Poisson / conditional tests as R's poisson.test (twins of codesplashr)
from codesplash.stats import means as csm # equivalence / non-inferiority lens (twin of cs_lens)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_rates.parquet", columns=["infections", "patient days", "arm"])
n_input = len(df)
df["arm"] = pd.Categorical(df["arm"], categories=["control", "treatment"]) # stored level order
df = df.dropna(subset=["infections", "patient days", "arm"]) # listwise deletion over the analysis columns
df["arm"] = df["arm"].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, ["infections", "patient days", "arm"]) # infinite values stop the run (registry/errors.yaml)
# %% Data checks
ev, ex = "infections", "patient days"
events = df[ev].to_numpy(dtype=float)
exposure = df[ex].to_numpy(dtype=float)
bad_counts = int(np.sum((events < 0) | (events != np.round(events))))
if bad_counts:
cs.cs_error("CS_E_INVALID_VALUES", column=ev, requirement="whole numbers ≥ 0 (event counts)", count=bad_counts)
if np.any(exposure <= 0):
cs.cs_error("CS_E_INVALID_VALUES", column=ex, requirement="above 0 on every row (time at risk or size)", count=int(np.sum(exposure <= 0)))
n = len(df)
per = 1000 # display scale: rates per this many units of exposure
alternative = "two-sided"
conf = 0.95
z = stats.norm.ppf(1 - (1 - conf) / 2)
X, T = int(events.sum()), float(exposure.sum())
values = {"n": n, "events_total": X, "exposure_total": T, "per": per}
notes = []
# %% Two rates: exact conditional test of the rate ratio (R's poisson.test(c(x1, x2), c(t1, t2), r))
g = "arm"
levels = [str(v) for v in df[g].cat.categories]
if len(levels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
reference = levels[0] # denominator of the rate ratio
if reference not in levels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=reference, column=g)
comparison = levels[1] if reference == levels[0] else levels[0]
grp = df[g].astype(str).to_numpy()
xc, tc = int(events[grp == comparison].sum()), float(exposure[grp == comparison].sum())
xr, tr = int(events[grp == reference].sum()), float(exposure[grp == reference].sum())
ratio0 = 1
rr = csc.rate_ratio_test(xc, tc, xr, tr, ratio0, alternative, conf)
# E-test of the rate difference λc − λr = δ0 (Krishnamoorthy & Thomson 2004), same direction as the alternative.
test = "exact"
diff0 = 0 # null rate difference on the display scale (per the units above)
et = stats.poisson_means_test(xc, tc, xr, tr, diff=diff0 / per, alternative=alternative)
p_exact, p_etest, z_etest = rr["p"], float(et.pvalue), float(et.statistic)
p = p_etest if test == "etest" else p_exact
test_label = "E-test" if test == "etest" else "exact conditional test"
diff = (xc / tc - xr / tr) * per
se_diff = math.sqrt(xc / tc**2 + xr / tr**2) * per
if xc > 0 and xr > 0:
se_log = math.sqrt(1 / xc + 1 / xr)
wald = (rr["ratio"] * math.exp(-z * se_log), rr["ratio"] * math.exp(z * se_log))
else:
wald = (math.nan, math.nan)
rows = []
for lv, x_, t_ in ((reference, xr, tr), (comparison, xc, tc)):
lo, hi = csc.garwood(x_, conf)
rows.append({"group": lv, "events": x_, "exposure": t_, "rate": x_ / t_ * per, "low": lo / t_ * per, "high": hi / t_ * per})
values.update({f"events[{lv}]": x_, f"exposure[{lv}]": t_, f"rate[{lv}]": x_ / t_ * per, f"rate_low[{lv}]": lo / t_ * per, f"rate_high[{lv}]": hi / t_ * per})
values.update({
"mode": "two-sample", "reference": reference, "comparison": comparison, "p": p, "p_exact": p_exact, "test_label": test_label, "diff0": diff0,
"estimate": rr["ratio"],
"ci_low": rr["ci_low"], "ci_high": rr["ci_high"], "ratio": rr["ratio"], "ratio_ci_low": rr["ci_low"], "ratio_ci_high": rr["ci_high"],
"p_etest": p_etest, "z_etest": z_etest, "diff": diff, "diff_ci_low": diff - z * se_diff, "diff_ci_high": diff + z * se_diff,
"ratio_wald_low": wald[0], "ratio_wald_high": wald[1], "rate_comp": xc / tc * per, "rate_ref": xr / tr * per,
})
summary = (f"Rate ratio {comparison} / {reference} = {cs.fmt_num(rr['ratio'])}, {conf:.0%} CI [{cs.fmt_num(rr['ci_low'])}, "
f"{cs.fmt_num(rr['ci_high'])}], exact conditional test {cs.fmt_p(p_exact)} (E-test {cs.fmt_p(p_etest)}).")
if test == "etest":
apa = f"E-test z = {cs.fmt_num(z_etest)}, {cs.fmt_p(p)}, rate difference = {cs.fmt_num(diff)} per {cs.fmt_num(per)}, {conf:.0%} CI [{cs.fmt_num(diff - z * se_diff)}, {cs.fmt_num(diff + z * se_diff)}]"
else:
apa = f"IRR = {cs.fmt_num(rr['ratio'])}, {conf:.0%} CI [{cs.fmt_num(rr['ci_low'])}, {cs.fmt_num(rr['ci_high'])}], {cs.fmt_p(p)}"
notes.append(f"The exact conditional test is of the rate ratio = {cs.fmt_num(ratio0)}; the E-test is of the rate difference = {cs.fmt_num(diff0)} per {cs.fmt_num(per)}.")
statistics = [
{"key": "p", "label": f"p ({test_label})", "value": p, "format": "p"},
{"key": "p_exact", "label": "p (exact conditional)", "value": p_exact, "format": "p"},
{"key": "z_etest", "label": "E-test statistic", "value": z_etest},
{"key": "p_etest", "label": "p (E-test)", "value": p_etest, "format": "p"},
]
effects = [
{"key": "ratio", "label": f"Rate ratio ({comparison} / {reference})", "value": rr["ratio"], "ciLow": rr["ci_low"], "ciHigh": rr["ci_high"],
"ciLevel": conf, "method": "exact (conditional binomial)"},
{"key": "diff", "label": f"Rate difference per {cs.fmt_num(per)}", "value": diff, "ciLow": diff - z * se_diff, "ciHigh": diff + z * se_diff,
"ciLevel": conf, "method": "Wald"},
]
# Lens on the rate ratio (equivalence / non-inferiority): log rate ratio with its Wald SE, normal
# reference, bounds entered as rate ratios and tested on the log scale (stream A's lens twin)
lens_kind = "none"
if lens_kind != "none":
lens_low, lens_high = None, None
if any(b is not None and b <= 0 for b in (lens_low, lens_high)):
raise ValueError("Lens bounds are rate ratios and must be positive (e.g. 0.8 and 1.25).")
if xc == 0 or xr == 0:
warnings.append("A group has no events, so the log rate ratio is undefined and the lens is not computed.")
else:
lens = csm.lens(lens_kind, math.log(rr["ratio"]), math.sqrt(1 / xc + 1 / xr), None,
None if lens_low is None else math.log(lens_low), None if lens_high is None else math.log(lens_high), 1 - conf)
lens["lens_ci_low"], lens["lens_ci_high"] = math.exp(lens["lens_ci_low"]), math.exp(lens["lens_ci_high"]) # back to the ratio scale
values.update(lens)
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
statistics.append({"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"})
notes.append(f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} Wald interval for the rate ratio.")
# %% Assumptions
assumptions = [
{"key": "poisson", "label": "Events occur independently at a constant rate", "status": "info",
"detail": "Exact Poisson tests assume no clustering; overdispersed counts make them anti-conservative (consider count regression)."},
{"key": "counts", "label": "Valid counts and exposure", "status": "pass", "detail": "Events are whole numbers ≥ 0 and exposure is > 0 on every row."},
]
# %% Result
cs.publish({
"method": "rates.poisson",
"methodVersion": "1.2.1",
"title": "Poisson rates",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": apa,
"statistics": statistics,
"tables": [{
"key": "rates", "title": f"Rates per {cs.fmt_num(per)} units of exposure",
"columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "events", "label": "Events", "type": "integer"},
{"key": "exposure", "label": "Exposure", "type": "number"}, {"key": "rate", "label": "Rate", "type": "number"},
{"key": "low", "label": "Lower (exact)", "type": "number"}, {"key": "high", "label": "Upper (exact)", "type": "number"}],
"rows": rows,
}],
"effectSizes": effects,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": [cs.chart(
"rates", "forest", f"Rate per {cs.fmt_num(per)}",
{"label": cs.col("group", [r["group"] for r in rows]), "estimate": cs.col(f"Rate per {cs.fmt_num(per)}", [r["rate"] for r in rows]),
"low": cs.col("low", [r["low"] for r in rows]), "high": cs.col("high", [r["high"] for r in rows])},
note="Exact (Garwood) intervals.",
)],
"values": values,
})
With more events, the gap between the two nearly closes. Across 142 infections and 12,718 patient days, the rate per 1,000 was 8.0 on treatment and 14.3 on control. The ratio is 0.56 (95% CI 0.39 to 0.80).
The exact test gives p < .001, and the E-test gives p < .001.
When counts vary too much
ExploreBoth tests assume the variance of a count equals its mean. Real counts are often more spread out: some patients are at higher risk, and infections cluster on a ward.
Lower the size setting to add spread, with no real difference between the groups. Watch how often the Poisson test rejects.
DExplorable · Overdispersed counts
What happens to a Poisson test when counts vary more than the Poisson allows?
With no real difference, how often does the plain Poisson comparison reject?
Commit your prediction above to see the result
Make your prediction to see the result.
If your counts look like this, a negative binomial model is the usual next step. The Regression track covers it.
Check your understanding
CheckpointCheck yourself
A ward has 15 infections over 5,000 patient days. What is the rate per 1,000 patient days?
Show the answer
Answer: 3
15 / 5,000 × 1,000 = 3.
Check yourself
Two groups have exposures of 30 and 70. If their rates are equal, what share of the events should fall in the first group?
Show the answer
Answer: 0.3
30 / (30 + 70) = 0.3. The exact conditional test compares the observed split with this share.
Check yourself
Clinic A had 20 events in 1,000 patient days. Clinic B had 30 events in 3,000 patient days. Which has the higher rate?
Show the answer
Answer: a
Rates divide by exposure. A test tells you how compatible the gap is with chance, but it doesn't decide which observed rate is higher.
Check yourself
Which situation most threatens a Poisson rate test?
Show the answer
Answer: b
Those events aren't independent and don't share one rate, so the variance exceeds the mean and p-values come out too small. Unequal exposure is exactly what the test handles.
Do it in CodeSplash
In the appChoose Events and Exposure. With no Group, the test compares one rate with the Reference rate. Add a group to compare two, and Test (two rates) chooses the exact conditional test or the E-test; the card reports the other's p-value as well. Rates per … units of exposure sets the scale.
import numpy as np
from scipy import stats
# One rate: exact test of 12 events in 100 against 8 per 100
pmf = stats.poisson(8).pmf(np.arange(200))
print(pmf[pmf <= pmf[12] * (1 + 1e-7)].sum())
# Two rates: exact conditional test, then the E-test
print(stats.binomtest(12, 19, 100 / 190).pvalue)
print(stats.poisson_means_test(12, 100, 7, 90))poisson.test(12, 100, r = 0.08)
poisson.test(c(12, 7), c(100, 90)) # exact conditional testBase R has no E-test.
Recap
Recap- Rates are events divided by exposure, so always say what the denominator is.
- Comparing two rates reduces to a binomial test on how the events split, which is why it's exact.
- The E-test has more power with few events. Overdispersion undermines both, however many events you have.
Concepts in this lesson