The expected-counts rule, and what to do when it fails
The rule of five is about expected counts, not observed ones. When a table is sparse, a Monte Carlo or exact p-value is one option away.
What runs in CodeSplash
- χ² test of independence Verified in Python and R
- Exact test of independence for R × C tables (Fisher–Freeman–Halton) Verified in Python and R
You will be able to
- State the rule of thumb for expected counts correctly
- Check a sparse table from the card's own output
- Replace the approximation with a Monte Carlo or exact p-value
What the rule says
ReadThe chi-square approximation works when expected counts aren't too small. The usual guide, from Cochran: at least 80% of cells have an expected count of 5 or more, and no cell is below 1.
Try to break it
ExploreShrink the sample and watch the expected counts fall. Compare the approximate p-value with the exact one. Does the first sparse cell immediately ruin the approximation, or does it go wrong more gradually?
EExplorable · The expected-counts rule
Is "every expected count at least 5" the right rule for a chi-square test?
With these margins, how often does Pearson's χ² reject when there is no association?
Commit your prediction above to see the result
Make your prediction to see the result.
Predict the damage
PredictPredict first
mtcars crosses cylinders with transmission: 32 cars in 6 cells. 3 cells have expected counts below 5, and the smallest is 2.84. The rule fails.
How far will the approximate p-value be from a Monte Carlo one, which doesn't rely on the approximation?
Reveal
They differ a little: approximate 0.0126, Monte Carlo 0.0140. The rule is a warning to check, not a verdict. In this table, the two agree well enough; in others they won't.
Your options
Read| Option | How | When |
|---|---|---|
| Monte Carlo p-value | Simulate tables with the same margins | Any size of table |
| Fisher–Freeman–Halton exact | Enumerate every table with these margins | Small tables |
| Combine categories | Merge rare levels | Only when the merged level still means something |
Exact enumeration is limited by how many tables exist. A 3 × 4 table of only 29 patients has up to 11,088 of them. There, 92% of cells are below 5.
Read the result
Readχ²(2, N = 32) = 8.74, p = .014, V = .46
- χ²
- 8.741
- df
- 2
- p (χ² test (Monte Carlo))
- .014
- G (likelihood ratio)
- 9.295
- p (G)
- .010
Effect size
- Cramér's V (bias-corrected) 0.4643 · medium
- Cramér's V 0.5226
Plots
Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).
View data
| am_f | count | cyl_f | adjusted residual |
|---|---|---|---|
| automatic | 3 | 4 | −2.676 |
| manual | 8 | 4 | 2.676 |
| automatic | 4 | 6 | −0.1360 |
| manual | 3 | 6 | 0.1360 |
| automatic | 12 | 8 | 2.676 |
| manual | 2 | 8 | −2.676 |
Assumptions
- Expected counts ≥ 5 — Monte Carlo p-value (2,000 permutations, seed 42); smallest expected count 2.84.
Observed counts
| cyl_f \ am_f | automatic | manual | Total |
|---|---|---|---|
| 4 | 3 | 8 | 11 |
| 6 | 4 | 3 | 7 |
| 8 | 12 | 2 | 14 |
Adjusted standardized residuals (|z| > 1.96 stands out)
| cyl_f \ am_f | automatic | manual |
|---|---|---|
| 4 | −2.676 | 2.676 |
| 6 | −0.1360 | 0.1360 |
| 8 | 2.676 | −2.676 |
- Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
The exact R script · R R version 4.5.1 (2025-06-13)
# χ² test of independence
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.chisq 1.3.1 · spec 2c6649f0759fa2ac
# 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_fisher_or, cs_chisq_mc, cs_power_divergence (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("cyl_f", "am_f")))
n_input <- nrow(df)
df[["cyl_f"]] <- factor(df[["cyl_f"]], levels = c("4", "6", "8")) # stored level order
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual")) # stored level order
df <- df[stats::complete.cases(df[c("cyl_f", "am_f")]), , 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("cyl_f", "am_f")) # 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
a <- "cyl_f"
b <- "am_f"
tab <- table(df[[a]], df[[b]]) # stored level order
row_levels <- rownames(tab)
col_levels <- colnames(tab)
nr <- nrow(tab)
nc <- ncol(tab)
n <- sum(tab)
if (nr < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a, min = 2, k = nr)
if (nc < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = b, min = 2, k = nc)
conf <- 0.95
want_fisher <- TRUE
use_mc <- TRUE
framing <- "independence" # independence (one sample, two variables) or homogeneity (groups compared)
statistic <- "pearson"
lam <- cs_pd_lambda(statistic, 0.6666666666666666) # Cressie–Read lambda (1 = Pearson, 0 = G²)
pd_label <- c(pearson = "Pearson χ²", g = "likelihood-ratio G²", cressie_read = "Cressie–Read", freeman_tukey = "Freeman–Tukey",
mod_g = "modified G²", neyman = "Neyman χ²")
res <- suppressWarnings(chisq.test(tab, correct = FALSE)) # pinned: no Yates correction; expected counts checked below
chi2 <- unname(res$statistic)
dof <- unname(res$parameter)
chi2_p <- res$p.value
expected <- res$expected
pos <- tab > 0
g <- 2 * sum(tab[pos] * log(tab[pos] / expected[pos])) # likelihood-ratio G
g_p <- pchisq(g, dof, lower.tail = FALSE)
# Power-divergence statistic chosen in the options (Cressie & Read 1984); Pearson's is chi-square itself
pd_stat <- if (statistic == "pearson") chi2 else cs_power_divergence(tab, expected, lam)
pd_p <- if (statistic == "pearson") chi2_p else if (is.finite(pd_stat)) pchisq(pd_stat, dof, lower.tail = FALSE) else NULL
if (is.null(pd_p)) {
warnings <- c(warnings, sprintf("The %s statistic is undefined when a cell is empty; Pearson's χ² is used instead.", pd_label[[statistic]]))
statistic <- "pearson"; lam <- 1; pd_stat <- chi2; pd_p <- chi2_p
}
rows_code <- as.integer(df[[a]])
cols_code <- as.integer(df[[b]])
mc_p <- NULL
if (use_mc) { # permutation p-value with fixed margins (seeded; identical in Python)
mc_p <- if (statistic == "pearson") {
cs_chisq_mc(rows_code, cols_code, nr, nc, expected, 2000, seed = 42)
} else {
cs_pd_chisq_mc(rows_code, cols_code, nr, nc, expected, 2000, 42, lam)
}
}
rs <- NULL
if (!is.null(rs)) {
p <- if (correction == "second_order") rs$p_f else rs$p_first
label <- if (correction == "second_order") "Rao–Scott F (second order)" else "Rao–Scott χ² (first order)"
} else {
p <- if (use_mc) mc_p else pd_p
label <- paste0(if (statistic == "pearson") "χ² test" else paste(pd_label[[statistic]], "test"), if (use_mc) " (Monte Carlo)" else "")
}
stdres <- res$stdres # adjusted residuals
cramers_v <- sqrt(chi2 / (n * (min(nr, nc) - 1)))
# Bias-corrected Cramer's V (Bergsma 2013)
phi2c <- max(0, chi2 / n - (nr - 1) * (nc - 1) / (n - 1))
rc <- nr - (nr - 1)^2 / (n - 1)
cc <- nc - (nc - 1)^2 / (n - 1)
cramers_v_corrected <- sqrt(phi2c / min(rc - 1, cc - 1))
min_expected <- min(expected)
cells_below_5 <- sum(expected < 5)
fisher <- NULL
if (want_fisher && nr == 2 && nc == 2) {
ft <- fisher.test(tab, conf.level = conf)
fo <- cs_fisher_or(tab[1, 1], tab[1, 2], tab[2, 1], tab[2, 2], conf) # conditional MLE solved to 1e-12
fisher <- list(p = ft$p.value, or = fo$or, low = fo$low, high = fo$high)
}
# %% Assumptions
status <- if (use_mc || !is.null(rs)) "info" else if (min_expected < 1) "fail" else if (cells_below_5 > 0) "warn" else "pass"
detail <- if (!is.null(rs)) {
sprintf("The design-based test does not rely on the unweighted expected counts (smallest %.2f).", min_expected)
} else if (use_mc) {
sprintf("Monte Carlo p-value (%s permutations, seed 42); smallest expected count %.2f.", format(2000, big.mark = ","), min_expected)
} else {
paste0(sprintf("Smallest expected count %.2f; %d of %d cells below 5.", min_expected, cells_below_5, nr * nc),
if (status != "pass") " Use Fisher's exact test or the Monte Carlo p-value." else "")
}
assumptions <- list(list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail))
if (!is.null(rs)) {
assumptions[[2]] <- list(key = "survey_design", label = "Sampling design accounted for", status = "pass",
detail = sprintf("Rao–Scott correction over %d primary sampling units in %d strata; mean design effect %.2f.",
as.integer(rs$n_psu), as.integer(rs$n_strata), rs$deff_mean))
}
# %% Result
alpha <- 1 - conf
s <- sqrt(min(nr, nc) - 1)
size <- magnitude(cramers_v_corrected, c(0.1, 0.3, 0.5) / s)
if (framing == "homogeneity") {
significance <- if (p < alpha) {
sprintf("The distribution of %s differs between the groups of %s (%s).", b, a, cs_fmt_p(p))
} else {
sprintf("The data are compatible with the same distribution of %s in every group of %s (%s).", b, a, cs_fmt_p(p))
}
test_name <- "homogeneity"
} else {
significance <- if (p < alpha) {
sprintf("%s and %s are associated (%s).", a, b, cs_fmt_p(p))
} else {
sprintf("The data are compatible with independence of %s and %s (%s).", a, b, cs_fmt_p(p))
}
test_name <- "independence"
}
summary <- sprintf("%s of %s on a %d × %d table of %d rows. %s The association is %s (bias-corrected Cramér's V = %.2f).",
label, test_name, nr, nc, as.integer(n), significance, size, cramers_v_corrected)
if (!is.null(fisher)) summary <- paste(summary, sprintf("Fisher's exact test: %s, conditional odds ratio %.2f.", cs_fmt_p(fisher$p), fisher$or))
values <- list(chi2 = chi2, df = dof, p = p, n = n, cramers_v = cramers_v, cramers_v_corrected = cramers_v_corrected,
min_expected = min_expected, cells_below_5 = cells_below_5, g = g, g_p = g_p, chi2_p = chi2_p, mc_p = mc_p,
fisher_p = if (is.null(fisher)) NULL else fisher$p, odds_ratio = if (is.null(fisher)) NULL else fisher$or,
or_ci_low = if (is.null(fisher)) NULL else fisher$low, or_ci_high = if (is.null(fisher)) NULL else fisher$high, nr = nr, nc = nc,
pd_stat = pd_stat, pd_lambda = lam, pd_p = pd_p, statistic_label = label,
rs_f = rs$f, rs_ndf = rs$ndf, rs_ddf = rs$ddf, rs_p = rs$p_f, rs_x2_first = rs$x2_first, rs_p_first = rs$p_first,
deff_mean = rs$deff_mean, n_psu = rs$n_psu, n_strata = rs$n_strata)
for (i in seq_len(nr)) {
for (j in seq_len(nc)) {
values[[sprintf("stdres[%s|%s]", row_levels[i], col_levels[j])]] <- stdres[i, j]
values[[sprintf("expected[%s|%s]", row_levels[i], col_levels[j])]] <- expected[i, j]
}
}
count_cols <- lapply(seq_len(nc), function(j) list(key = sprintf("c%d", j - 1), label = col_levels[j], type = "integer"))
columns <- c(list(list(key = "row", label = paste(a, "\\", b), type = "string")), count_cols, list(list(key = "total", label = "Total", type = "integer")))
counts <- lapply(seq_len(nr), function(i) {
c(list(row = row_levels[i]), stats::setNames(as.list(as.integer(tab[i, ])), sprintf("c%d", seq_len(nc) - 1)), list(total = as.integer(sum(tab[i, ]))))
})
residual_rows <- lapply(seq_len(nr), function(i) c(list(row = row_levels[i]), stats::setNames(as.list(unname(stdres[i, ])), sprintf("c%d", seq_len(nc) - 1))))
residual_cols <- c(list(list(key = "row", label = paste(a, "\\", b), type = "string")),
lapply(count_cols, function(cl) { cl$type <- "number"; cl }))
effect_sizes <- list(
list(key = "cramers_v_corrected", label = "Cramér's V (bias-corrected)", value = cramers_v_corrected, method = "Bergsma (2013)",
magnitude = size, ruleSet = "Cohen (1988), w / √(min(r, c) − 1)"),
list(key = "cramers_v", label = "Cramér's V", value = cramers_v, method = "√(χ² / (n (min(r, c) − 1)))")
)
if (!is.null(fisher)) {
effect_sizes[[3]] <- list(key = "odds_ratio", label = "Odds ratio (conditional MLE)", value = fisher$or, ciLow = fisher$low,
ciHigh = fisher$high, ciLevel = conf, method = "Fisher's exact test")
}
cell_row <- rep(row_levels, each = nc)
cell_col <- rep(col_levels, times = nr)
cs_publish(list(
method = "contingency.chisq",
methodVersion = "1.3.1",
title = if (framing == "homogeneity") "χ² test of homogeneity" else "χ² test of independence",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = if (!is.null(rs) && correction == "second_order") {
sprintf("Rao–Scott F(%s, %s) = %s, %s", cs_fmt_num(rs$ndf), cs_fmt_num(rs$ddf), cs_fmt_num(rs$f), cs_fmt_p(p))
} else if (!is.null(rs)) {
sprintf("Rao–Scott χ²(%d) = %s, %s", as.integer(dof), cs_fmt_num(rs$x2_first), cs_fmt_p(p))
} else if (statistic == "pearson") {
sprintf("χ²(%d, N = %d) = %s, %s, V = %s", dof, as.integer(n), cs_fmt_num(chi2), cs_fmt_p(p), cs_fmt_num(cramers_v_corrected, leading_zero = FALSE))
} else {
sprintf("%s (λ = %s)(%d, N = %d) = %s, %s, V = %s", pd_label[[statistic]], cs_fmt_num(lam), as.integer(dof), as.integer(n), cs_fmt_num(pd_stat),
cs_fmt_p(p), cs_fmt_num(cramers_v_corrected, leading_zero = FALSE))
},
statistics = c(list(list(key = "chi2", label = "χ²", value = chi2), list(key = "df", label = "df", value = dof),
list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p"),
list(key = "g", label = "G (likelihood ratio)", value = g), list(key = "g_p", label = "p (G)", value = g_p, format = "p")),
if (!statistic %in% c("pearson", "g")) list(
list(key = "pd_stat", label = sprintf("%s (λ = %s)", pd_label[[statistic]], format(signif(lam, 3))), value = pd_stat),
list(key = "pd_p", label = sprintf("p (%s)", pd_label[[statistic]]), value = pd_p, format = "p")),
if (!is.null(rs)) list(
list(key = "rs_f", label = "Rao–Scott F", value = rs$f), list(key = "rs_ndf", label = "df (numerator)", value = rs$ndf),
list(key = "rs_ddf", label = "df (denominator)", value = rs$ddf), list(key = "rs_p", label = "p (Rao–Scott F)", value = rs$p_f, format = "p"),
list(key = "rs_x2_first", label = "Rao–Scott χ² (first order)", value = rs$x2_first),
list(key = "rs_p_first", label = "p (first order)", value = rs$p_first, format = "p"),
list(key = "deff_mean", label = "Mean design effect", value = rs$deff_mean)),
if (!is.null(fisher)) list(list(key = "fisher_p", label = "Fisher's exact p", value = fisher$p, format = "p"))),
tables = list(
list(key = "observed", title = "Observed counts", columns = columns, rows = counts),
list(key = "stdres", title = "Adjusted standardized residuals (|z| > 1.96 stands out)", columns = residual_cols, rows = residual_rows)
),
effectSizes = effect_sizes,
assumptions = assumptions,
warnings = warnings,
notes = c(list("Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals."),
if (!is.null(rs)) list("Counts, χ², G, Cramér's V and the residuals describe the unweighted sample; the p-value is design-based (Rao–Scott).")),
charts = list(cs_chart(
"residuals", "matrix-heatmap", sprintf("Adjusted residuals: %s × %s", a, b),
list(row = cs_col(a, cell_row, levels = row_levels), col = cs_col(b, cell_col, levels = col_levels),
value = cs_col("adjusted residual", as.numeric(t(stdres))), label = cs_col("count", as.character(as.integer(t(tab))))),
controls = list(scale = "diverging"), note = "Cells show counts; color is the adjusted residual (|z| > 1.96 stands out)."
)),
values = values
))
χ²(2, N = 32) = 8.74, p = .014, V = .46
- χ²
- 8.741
- df
- 2
- p (χ² test (Monte Carlo))
- .014
- G (likelihood ratio)
- 9.295
- p (G)
- .010
Effect size
- Cramér's V (bias-corrected) 0.4643 · medium
- Cramér's V 0.5226
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts ≥ 5 — Monte Carlo p-value (2,000 permutations, seed 42); smallest expected count 2.84.
Observed counts
| cyl_f \ am_f | automatic | manual | Total |
|---|---|---|---|
| 4 | 3 | 8 | 11 |
| 6 | 4 | 3 | 7 |
| 8 | 12 | 2 | 14 |
Adjusted standardized residuals (|z| > 1.96 stands out)
| cyl_f \ am_f | automatic | manual |
|---|---|---|
| 4 | −2.676 | 2.676 |
| 6 | −0.1360 | 0.1360 |
| 8 | 2.676 | −2.676 |
- Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# χ² test of independence
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.chisq 1.3.1 · spec 2c6649f0759fa2ac
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # Monte Carlo p (twin of codesplashr::cs_chisq_mc)
from codesplash.stats import proportions_ext as csx # power-divergence family (twins of cs_power_divergence …)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["cyl_f", "am_f"])
n_input = len(df)
df["cyl_f"] = pd.Categorical(df["cyl_f"], categories=["4", "6", "8"]) # stored level order
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"]) # stored level order
df = df.dropna(subset=["cyl_f", "am_f"]) # listwise deletion over the analysis columns
df["cyl_f"] = df["cyl_f"].cat.remove_unused_categories()
df["am_f"] = df["am_f"].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, ["cyl_f", "am_f"]) # 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
a, b = "cyl_f", "am_f"
table = pd.crosstab(df[a], df[b], dropna=False) # stored level order
observed = table.to_numpy(dtype=float)
row_levels = [str(v) for v in table.index]
col_levels = [str(v) for v in table.columns]
nr, nc = observed.shape
n = float(observed.sum())
if nr < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a, min=2, k=nr)
if nc < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=b, min=2, k=nc)
conf = 0.95
want_fisher = True
use_mc = True
framing = "independence" # independence (one sample, two variables) or homogeneity (groups compared)
statistic = "pearson"
lam = csx.pd_lambda(statistic, 0.6666666666666666) # Cressie–Read λ (1 = Pearson, 0 = G²)
chi2, chi2_p, dof, expected = stats.chi2_contingency(observed, correction=False) # pinned: no Yates correction
chi2, chi2_p = float(chi2), float(chi2_p)
pos = observed > 0
g = float(2 * np.sum(observed[pos] * np.log(observed[pos] / expected[pos]))) # likelihood-ratio G
g_p = float(stats.chi2.sf(g, dof))
# Power-divergence statistic chosen in the options (Cressie & Read 1984); Pearson's is χ² itself
pd_stat = chi2 if statistic == "pearson" else csx.power_divergence(observed, expected, lam)
pd_p = chi2_p if statistic == "pearson" else (float(stats.chi2.sf(pd_stat, dof)) if math.isfinite(pd_stat) else None)
if pd_p is None:
warnings.append(f"The {csx.PD_LABEL[statistic]} statistic is undefined when a cell is empty; Pearson's χ² is used instead.")
statistic, lam, pd_stat, pd_p = "pearson", 1.0, chi2, chi2_p
rows_code = np.array([row_levels.index(str(x)) for x in df[a]])
cols_code = np.array([col_levels.index(str(x)) for x in df[b]])
mc_p = None
if use_mc: # permutation p-value with fixed margins (seeded; identical in R)
if statistic == "pearson":
mc_p = csp.chisq_mc(rows_code, cols_code, nr, nc, expected, int(2000), seed=42)
else:
mc_p = csx.pd_chisq_mc(rows_code, cols_code, nr, nc, expected, int(2000), 42, lam)
rs = None
if rs is not None:
p = rs["p_f"] if correction == "second_order" else rs["p_first"]
label = "Rao–Scott F (second order)" if correction == "second_order" else "Rao–Scott χ² (first order)"
else:
p = mc_p if use_mc else pd_p
label = ("χ² test" if statistic == "pearson" else f"{csx.PD_LABEL[statistic]} test") + (" (Monte Carlo)" if use_mc else "")
row_p = observed.sum(axis=1, keepdims=True) / n
col_p = observed.sum(axis=0, keepdims=True) / n
stdres = (observed - expected) / np.sqrt(expected * (1 - row_p) * (1 - col_p)) # adjusted residuals (R's $stdres)
cramers_v = float(np.sqrt(chi2 / (n * (min(nr, nc) - 1))))
# Bias-corrected Cramér's V (Bergsma 2013)
phi2c = max(0.0, chi2 / n - (nr - 1) * (nc - 1) / (n - 1))
rc, cc = nr - (nr - 1) ** 2 / (n - 1), nc - (nc - 1) ** 2 / (n - 1)
cramers_v_corrected = float(np.sqrt(phi2c / min(rc - 1, cc - 1)))
min_expected = float(expected.min())
cells_below_5 = int((expected < 5).sum())
fisher = None
if want_fisher and (nr, nc) == (2, 2):
fisher_p = float(stats.fisher_exact(observed)[1])
orr = stats.contingency.odds_ratio(observed.astype(int), kind="conditional") # conditional MLE (R's fisher.test)
or_ci = orr.confidence_interval(confidence_level=conf)
fisher = {"p": fisher_p, "or": float(orr.statistic), "low": float(or_ci.low), "high": float(or_ci.high)}
# %% Assumptions
warnings = list(warnings)
if use_mc or rs is not None:
status = "info"
elif min_expected < 1:
status = "fail"
elif cells_below_5:
status = "warn"
else:
status = "pass"
if rs is not None:
detail = f"The design-based test does not rely on the unweighted expected counts (smallest {min_expected:.2f})."
elif use_mc:
detail = f"Monte Carlo p-value ({int(2000):,} permutations, seed 42); smallest expected count {min_expected:.2f}."
else:
detail = (
f"Smallest expected count {min_expected:.2f}; {cells_below_5} of {nr * nc} cells below 5."
+ (" Use Fisher's exact test or the Monte Carlo p-value." if status != "pass" else "")
)
assumptions = [{"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail}]
if rs is not None:
assumptions.append({"key": "survey_design", "label": "Sampling design accounted for", "status": "pass",
"detail": f"Rao–Scott correction over {rs['n_psu']} primary sampling units in {rs['n_strata']} strata; "
f"mean design effect {rs['deff_mean']:.2f}."})
# %% Result
alpha = 1 - conf
size = magnitude(cramers_v_corrected, (0.1 / np.sqrt(min(nr, nc) - 1), 0.3 / np.sqrt(min(nr, nc) - 1), 0.5 / np.sqrt(min(nr, nc) - 1)))
if framing == "homogeneity":
significance = (
f"The distribution of {b} differs between the groups of {a} ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with the same distribution of {b} in every group of {a} ({cs.fmt_p(p)})."
)
test_name = "homogeneity"
else:
significance = (
f"{a} and {b} are associated ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with independence of {a} and {b} ({cs.fmt_p(p)})."
)
test_name = "independence"
summary = f"{label} of {test_name} on a {nr} × {nc} table of {int(n)} rows. {significance} The association is {size} (bias-corrected Cramér's V = {cramers_v_corrected:.2f})."
if fisher:
summary += f" Fisher's exact test: {cs.fmt_p(fisher['p'])}, conditional odds ratio {fisher['or']:.2f}."
values = {"chi2": chi2, "df": float(dof), "p": p, "n": int(n), "cramers_v": cramers_v, "cramers_v_corrected": cramers_v_corrected,
"min_expected": min_expected, "cells_below_5": cells_below_5, "g": g, "g_p": g_p, "chi2_p": chi2_p, "mc_p": mc_p,
"fisher_p": fisher["p"] if fisher else None, "odds_ratio": fisher["or"] if fisher else None,
"or_ci_low": fisher["low"] if fisher else None, "or_ci_high": fisher["high"] if fisher else None, "nr": nr, "nc": nc,
"pd_stat": pd_stat, "pd_lambda": lam, "pd_p": pd_p, "statistic_label": label,
"rs_f": rs["f"] if rs else None, "rs_ndf": rs["ndf"] if rs else None, "rs_ddf": rs["ddf"] if rs else None,
"rs_p": rs["p_f"] if rs else None, "rs_x2_first": rs["x2_first"] if rs else None, "rs_p_first": rs["p_first"] if rs else None,
"deff_mean": rs["deff_mean"] if rs else None, "n_psu": rs["n_psu"] if rs else None, "n_strata": rs["n_strata"] if rs else None}
for i, rl in enumerate(row_levels):
for j, cl in enumerate(col_levels):
values[f"stdres[{rl}|{cl}]"] = float(stdres[i, j])
values[f"expected[{rl}|{cl}]"] = float(expected[i, j])
columns = [{"key": "row", "label": f"{a} \\ {b}", "type": "string"}] + [
{"key": f"c{j}", "label": cl, "type": "integer"} for j, cl in enumerate(col_levels)] + [{"key": "total", "label": "Total", "type": "integer"}]
counts = [{"row": rl, **{f"c{j}": int(observed[i, j]) for j in range(nc)}, "total": int(observed[i].sum())} for i, rl in enumerate(row_levels)]
residual_rows = [{"row": rl, **{f"c{j}": float(stdres[i, j]) for j in range(nc)}} for i, rl in enumerate(row_levels)]
effect_sizes = [
{"key": "cramers_v_corrected", "label": "Cramér's V (bias-corrected)", "value": cramers_v_corrected, "method": "Bergsma (2013)",
"magnitude": size, "ruleSet": "Cohen (1988), w / √(min(r, c) − 1)"},
{"key": "cramers_v", "label": "Cramér's V", "value": cramers_v, "method": "√(χ² / (n (min(r, c) − 1)))"},
]
if fisher:
effect_sizes.append({"key": "odds_ratio", "label": "Odds ratio (conditional MLE)", "value": fisher["or"], "ciLow": fisher["low"],
"ciHigh": fisher["high"], "ciLevel": conf, "method": "Fisher's exact test"})
cells = [(rl, cl, float(stdres[i, j]), int(observed[i, j])) for i, rl in enumerate(row_levels) for j, cl in enumerate(col_levels)]
cs.publish({
"method": "contingency.chisq",
"methodVersion": "1.3.1",
"title": "χ² test of homogeneity" if framing == "homogeneity" else "χ² test of independence",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": (
f"Rao–Scott F({cs.fmt_num(rs['ndf'])}, {cs.fmt_num(rs['ddf'])}) = {cs.fmt_num(rs['f'])}, {cs.fmt_p(p)}" if rs is not None and correction == "second_order"
else f"Rao–Scott χ²({dof}) = {cs.fmt_num(rs['x2_first'])}, {cs.fmt_p(p)}" if rs is not None
else f"χ²({dof}, N = {int(n)}) = {cs.fmt_num(chi2)}, {cs.fmt_p(p)}, V = {cs.fmt_num(cramers_v_corrected, leading_zero=False)}" if statistic == "pearson"
else f"{csx.PD_LABEL[statistic]} (λ = {cs.fmt_num(lam)})({dof}, N = {int(n)}) = {cs.fmt_num(pd_stat)}, {cs.fmt_p(p)}, V = {cs.fmt_num(cramers_v_corrected, leading_zero=False)}"
),
"statistics": [{"key": "chi2", "label": "χ²", "value": chi2}, {"key": "df", "label": "df", "value": dof},
{"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
{"key": "g", "label": "G (likelihood ratio)", "value": g}, {"key": "g_p", "label": "p (G)", "value": g_p, "format": "p"}]
+ ([{"key": "pd_stat", "label": f"{csx.PD_LABEL[statistic]} (λ = {lam:.3g})", "value": pd_stat},
{"key": "pd_p", "label": f"p ({csx.PD_LABEL[statistic]})", "value": pd_p, "format": "p"}] if statistic not in ("pearson", "g") else [])
+ ([{"key": "rs_f", "label": "Rao–Scott F", "value": rs["f"]}, {"key": "rs_ndf", "label": "df (numerator)", "value": rs["ndf"]},
{"key": "rs_ddf", "label": "df (denominator)", "value": rs["ddf"]}, {"key": "rs_p", "label": "p (Rao–Scott F)", "value": rs["p_f"], "format": "p"},
{"key": "rs_x2_first", "label": "Rao–Scott χ² (first order)", "value": rs["x2_first"]},
{"key": "rs_p_first", "label": "p (first order)", "value": rs["p_first"], "format": "p"},
{"key": "deff_mean", "label": "Mean design effect", "value": rs["deff_mean"]}] if rs is not None else [])
+ ([{"key": "fisher_p", "label": "Fisher's exact p", "value": fisher["p"], "format": "p"}] if fisher else []),
"tables": [
{"key": "observed", "title": "Observed counts", "columns": columns, "rows": counts},
{"key": "stdres", "title": "Adjusted standardized residuals (|z| > 1.96 stands out)",
"columns": [{**c, "type": "number"} if c["key"].startswith("c") else c for c in columns[:-1]], "rows": residual_rows},
],
"effectSizes": effect_sizes,
"assumptions": assumptions,
"warnings": warnings,
"notes": ["Pearson χ² without continuity correction; residuals are adjusted (standardized) residuals."]
+ (["Counts, χ², G, Cramér's V and the residuals describe the unweighted sample; the p-value is design-based (Rao–Scott)."] if rs is not None else []),
"charts": [cs.chart(
"residuals", "matrix-heatmap", f"Adjusted residuals: {a} × {b}",
{"row": cs.col(a, [c[0] for c in cells], levels=row_levels), "col": cs.col(b, [c[1] for c in cells], levels=col_levels),
"value": cs.col("adjusted residual", [c[2] for c in cells]), "label": cs.col("count", [str(c[3]) for c in cells])},
controls={"scale": "diverging"}, note="Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).",
)],
"values": values,
})
Simulated on the shared random stream, the Monte Carlo p-value matches in Python and R. It's still limited by the simulation count, so the card reports how many it used.
Check your understanding
CheckpointCheck yourself
A cell has an observed count of 2 and an expected count of 9. Does it violate the rule?
Show the answer
Answer: b
Small observed counts can be the signal itself. The approximation depends on expected counts.
Check yourself
A 2 × 2 table has expected counts 4, 3, 12 and 6. What percentage of its cells have an expected count below 5?
Show the answer
Answer: 50
4 and 3 are below 5, so that's 2 of 4 cells, or 50%. The rule of thumb allows at most 20%.
Check yourself
A 5 × 4 table has several sparse cells. Which response is most defensible?
Show the answer
Answer: a
Dropping or tuning categories changes the question and invites bias. Monte Carlo keeps the question intact.
Check yourself
Why might you pick a Monte Carlo p-value over full enumeration for a large table?
Show the answer
Answer: a
Both condition on the same margins and ask the same question. Monte Carlo samples those tables rather than listing them, so its p-value carries some simulation error.
Do it in CodeSplash
In the appThe chi-square card reports the smallest expected count and how many cells are below 5. Turn on Monte Carlo p-value and set Simulations, or use the exact test for R × C tables, whose p-value can choose for you.
import numpy as np
import pandas as pd
from scipy import stats
df = pd.read_csv("mtcars.csv")
table = pd.crosstab(df["cyl_f"], df["am_f"]).to_numpy()
res = stats.chi2_contingency(table, correction=False)
print(res.pvalue, res.expected_freq)
# Monte Carlo: simulate tables with the same margins.
def x2(t):
e = np.outer(t.sum(1), t.sum(0)) / t.sum()
return ((t - e) ** 2 / e).sum()
sims = stats.random_table(table.sum(1), table.sum(0), seed=1).rvs(2000)
print((1 + sum(x2(s) >= res.statistic for s in sims)) / 2001)table <- with(mtcars, table(cyl, am))
chisq.test(table, correct = FALSE)$expected
chisq.test(table, simulate.p.value = TRUE, B = 2000)
fisher.test(table)Recap
Recap- The rule of five concerns expected counts.
- When it fails, a Monte Carlo or exact p-value keeps the same question.
- Merge categories only for reasons that come before the results.
Concepts in this lesson