Skip to content

EProportions & counts · rates.poisson

Poisson rates (one rate or two rates compared)

Is an event rate (events per unit of exposure) different from a reference value or between two groups?

Event rates per unit of exposure (person-time, area, volume): one rate against a reference value with the exact Poisson test and Garwood interval, or two groups compared with the exact conditional test of the rate ratio (and its exact interval), Krishnamoorthy–Thomson's E-test, and the rate difference with a Wald interval.

Verified in Python and R Python and R agree to 10 decimals Also called exact Poisson test, poisson.test, comparison of Poisson rates…

A real result

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

Poisson ratesRecorded · Python and R agreeRecorded 2026-11-17 · 36 values compared
R

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]

Plots

Rate per 1000.00How large are several estimates, how precise, and which exclude the null?

Exact (Garwood) intervals.

View data
Rate per 1000.00highgrouplow
14.30617.565control11.518
8.02310.548treatment5.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

GroupEventsExposureRateLower (exact)Upper (exact)
control916,36114.30611.51817.565
treatment516,3578.0235.97310.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.
Python

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

GroupEventsExposureRateLower (exact)Upper (exact)
control916,36114.30611.51817.565
treatment516,3578.0235.97310.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.

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

  • Two armss4_rates · events: infections · exposure: patient days · group: arm
  • One rates4_rates · events: infections · exposure: patient days
  • Ratio greater 90s4_rates · events: infections · exposure: patient days · group: arm
  • One rate two sideds4_rates · events: infections · exposure: patient days
  • One rate guidee_guide_rate · events: events · exposure: exposure
  • Two rates exact guidee_guide_rates · events: events · exposure: exposure · group: group
  • Two rates etest guidee_guide_rates · events: events · exposure: exposure · group: group
  • Lens equivalence guidee_guide_rates · events: events · exposure: exposure · group: group

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Counts, rates and ordinal outcomes · Statistics Guide · B — Compare groups
  • Count outcome: Poisson / negative binomial / zero-inflated · Statistics Guide · D — Predict an outcome
  • One group vs a known proportion · Statistics Guide · E — Compare proportions / frequencies
  • Two independent proportions · Statistics Guide · E — Compare proportions / frequencies

What you need

Eventsnumeric · 1 column
Number of events per row (non-negative whole numbers).
Exposurenumeric · 1 column
Time at risk, population or size per row (> 0).
Groupcategorical / boolean · 0–1 column · 2–2 levels
Two groups to compare (leave empty to test one rate against a reference value).

Choices you make

statistics

Rates per … units of exposuredefault 1000

Display scale: rates are reported per this many units of exposure (e.g. per 1,000 person-days).

hypothesis

Reference ratedefault 1

One rate: the rate under the null hypothesis, on the display scale (per the units above).

Null rate ratiodefault 1

Two rates: the rate ratio (second group / reference group) under the null hypothesis.

Reference groupdefault —

The group in the denominator of the rate ratio (default the first stored level).

Alternativedefault two-sided

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

  • Two-sided(default) — Plans for a test in either direction; the usual choice, though it needs more data than one-sided.
  • Greater (rate / ratio above the null value) — Tests only for a rate or ratio above the null value; pick it only if you fixed this direction before seeing the data.
  • Less (rate / ratio below the null value) — Tests only for a rate or ratio below the null value; pick it only if you fixed this direction before seeing the data.
Test (two rates)default exact

The primary test for two rates. Both are reported.

  • Exact conditional test (rate ratio)(default) — Conditions on the total count: a binomial test of how the events split between the groups (R's poisson.test).
  • E-test (rate difference) — Krishnamoorthy & Thomson's unconditional test; more powerful than the conditional test, especially with few events.
Null rate differencedefault 0

E-test: the difference in rates (comparison − reference, on the display scale) under the null hypothesis.

Confidence leveldefault 0.95

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

Lensdefault none

Also test against bounds you set before seeing the data: equivalence, a minimal effect or non-inferiority.

  • Off(default) — Test for a difference only.
  • Equivalence (TOST) — Show the effect lies inside your bounds (two one-sided tests).
  • Non-inferiority — Show the effect is not worse than the lower bound.
Lower bound (rate ratio)default —

The smallest effect that matters on the low side (for non-inferiority: the margin, as a negative number).

Upper bound (rate ratio)default —

The smallest effect that matters on the high side.

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.

  • Events occur independently at a constant rate

    Within each group events follow a Poisson process; clustering or overdispersion makes the exact tests anti-conservative (consider count regression).

  • Valid counts and exposure

    Events are whole numbers ≥ 0 and exposure is > 0.

What it reports

  • Tests: Rate (ratio) equals the null value
n
How many independent units the analysis used; it sets precision and power.
mode
one-sample (one rate against a reference rate) or two-sample (the rates of two groups compared).
events_total
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
exposure_total
How much opportunity each row had to produce the count (policy-years, hours, area), so the model learns a rate.
per
Rates are expressed per this many units of exposure. It changes only the display scale, not the test.
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.
estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.

Per group, level or term: events[<group>], exposure[<group>], rate[<group>], rate_low[<group>], rate_high[<group>], ratio, ratio_ci_low, ratio_ci_high, p_etest, z_etest, p_exact, test_label, diff0, diff, diff_ci_low, diff_ci_high, ratio_wald_low, ratio_wald_high, reference, comparison, rate_comp, rate_ref, lens_p (when a lens is on), lens_ci_low (when a lens is on), lens_ci_high (when a lens is on), lens_verdict (when a lens is on)

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

  • R calls poisson.test; Python uses twins that follow its two-sided rule (outcomes no more probable than the observed, relative tolerance 1 + 1e-7) and its gamma/beta intervals. The E-test is scipy.stats.poisson_means_test in Python and its port (cs_cnt_etest) in R; the tail truncation can move a bound by one count (mass < 1e-10).
Python

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

The exact script CodeSplash ran for example “Two arms” · 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
))

Sources

  • Garwood, F. (1936). Fiducial limits for the Poisson distribution. Biometrika, 28, 437–442.
  • Krishnamoorthy, K., & Thomson, J. (2004). A more powerful test for comparing two Poisson means. Journal of Statistical Planning and Inference, 119, 23–35.
  • Ulm, K. (1990). A simple method to calculate the confidence interval of a standardized mortality ratio. American Journal of Epidemiology, 131, 373–375.

From the CodeSplash method registry · rates.poisson v1.2.1.