Skip to content

Larger tables: chi-square, G and exact tests

Observed against expected is the whole idea. Learn the chi-square and G statistics, what independence and homogeneity mean, and how to find where a table differs.

Introductory ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Compute expected counts from a table's margins
  • Tell the independence and homogeneity framings apart
  • Use residuals and Cramér's V to describe the pattern

Read first

01

Observed against expected

Read

If hair and eye color were unrelated, each cell's count would follow from the margins alone:

Eij=(row i total)(column j total)nE_{ij} = \frac{(\text{row } i \text{ total})(\text{column } j \text{ total})}{n}

The chi-square statisticChi-square statisticA sum of squared, scaled differences between observed and expected counts or estimates. sums the squared gaps, scaled by what you expected:

X2=∑ij(Oij−Eij)2Eij,ν=(r−1)(c−1)X^2 = \sum_{ij} \frac{(O_{ij} - E_{ij})^2}{E_{ij}}, \qquad \nu = (r - 1)(c - 1)
02

Compare cell by cell

Explore

Edit the observed counts and watch each cell's contribution to X2X^2. Which cells move the statistic most? A gap of the same size counts for more when the expected count is small.

EExplorable · Observed against expected

How does a chi-square test turn a table of counts into one number?

What will the p-value be for this table?

0.50
How sure?
22
15
10
14
18
18
ABC
Row 1
22
expected 17.4
residual 1.09
15
expected 16.0
residual −0.25
10
expected 13.6
residual −0.97
Row 2
14
expected 18.6
residual −1.06
18
expected 17.0
residual 0.24
18
expected 14.4
residual 0.94

Shading shows how far each cell sits from its expected count. Residuals above about 2 stand out.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Predict the verdict

Predict

Predict first

Across 592 students, hair and eye color give X2X^2 = 138.3 on 9 degrees of freedom, p < .001.

How strong is the association on a 0-to-1 scale? Drag to your guess.

Make your guess between 0 and 1 Cramér's V, then reveal.

Reveal

Cramér's VCramér's VAssociation strength in a contingency table, from 0 (none) to 1 (perfect). = 0.28: moderate. A huge X2X^2 can come from a modest association in a large sample. Report V alongside the test.

04

One test, two questions

Read

Independence: you sampled one group and cross-classified it. Are the two variables related?

Homogeneity: you sampled separate groups. Do they have the same distribution?

The arithmetic is identical, but the sentence differs. Two groups of 30 give X2X^2 = 5.45, p = .020. That's the same p-value as their two-proportion z test: p = .020.

05

G, and exact versions

Read

The likelihood-ratio statistic G2=2∑Oln⁡(O/E)G^2 = 2\sum O \ln(O/E) asks the same question: here 146.4. For large samples the two agree.

With sparse tables, use the Fisher–Freeman–Halton exact test. On a 3 × 4 table of 29 patients, the χ2\chi^2 approximation gives p = .627 and the exact test gives p = .653.

06

Read the result

Read
χ² test of independenceRecorded · Python and R agreeRecorded 2026-11-25 · 63 values compared
R

χ²(9, N = 592) = 138.29, p < .001, V = .27

χ²
138.29
df
9
p (χ² test)
< .001
G (likelihood ratio)
146.44
p (G)
< .001

Effect size

  • Cramér's V (bias-corrected) 0.2705 · medium
  • Cramér's V 0.2790

Plots

Adjusted residuals: hair × eyeWhat do the values of a square or rectangular result matrix look like at a glance?

Cells show counts; color is the adjusted residual (|z| > 1.96 stands out).

View data
eyecounthairadjusted residual
Brown68Black6.137
Blue20Black−4.254
Hazel15Black−0.5750
Green5Black−2.288
Brown119Brown2.164
Blue84Brown−3.398
Hazel54Brown2.050
Green29Brown−0.5083
Brown26Red−0.1008
Blue17Red−2.311
Hazel14Red0.9895
Green14Red2.577
Brown7Blond−8.328
Blue94Blond9.968
Hazel10Blond−2.738
Green16Blond0.7320

Assumptions

  • Expected counts ≥ 5 — Smallest expected count 7.68; 0 of 16 cells below 5.

Observed counts

hair \ eyeBrownBlueHazelGreenTotal
Black6820155108
Brown119845429286
Red2617141471
Blond7941016127

Adjusted standardized residuals (|z| > 1.96 stands out)

hair \ eyeBrownBlueHazelGreen
Black6.137−4.254−0.5750−2.288
Brown2.164−3.3982.050−0.5083
Red−0.1008−2.3110.98952.577
Blond−8.3289.968−2.7380.7320
  • 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 5730ffa1002cf7dc
# 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_fisher_or, cs_chisq_mc, cs_power_divergence (twins of codesplash.stats)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hair_eye.parquet", col_select = c("hair", "eye")))
n_input <- nrow(df)
df[["hair"]] <- factor(df[["hair"]], levels = c("Black", "Brown", "Red", "Blond"))  # stored level order
df[["eye"]] <- factor(df[["eye"]], levels = c("Brown", "Blue", "Hazel", "Green"))  # stored level order
df <- df[stats::complete.cases(df[c("hair", "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("hair", "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
a <- "hair"
b <- "eye"
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 <- FALSE
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, 5000, seed = 42)
  } else {
    cs_pd_chisq_mc(rows_code, cols_code, nr, nc, expected, 5000, 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(5000, 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
))
Python

χ²(9, N = 592) = 138.29, p < .001, V = .27

χ²
138.29
df
9
p (χ² test)
< .001
G (likelihood ratio)
146.44
p (G)
< .001

Effect size

  • Cramér's V (bias-corrected) 0.2705 · medium
  • Cramér's V 0.2790

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Expected counts ≥ 5 — Smallest expected count 7.68; 0 of 16 cells below 5.

Observed counts

hair \ eyeBrownBlueHazelGreenTotal
Black6820155108
Brown119845429286
Red2617141471
Blond7941016127

Adjusted standardized residuals (|z| > 1.96 stands out)

hair \ eyeBrownBlueHazelGreen
Black6.137−4.254−0.5750−2.288
Brown2.164−3.3982.050−0.5083
Red−0.1008−2.3110.98952.577
Blond−8.3289.968−2.7380.7320
  • 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 5730ffa1002cf7dc
# 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 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/hair_eye.parquet", columns=["hair", "eye"])
n_input = len(df)
df["hair"] = pd.Categorical(df["hair"], categories=["Black", "Brown", "Red", "Blond"])  # stored level order
df["eye"] = pd.Categorical(df["eye"], categories=["Brown", "Blue", "Hazel", "Green"])  # stored level order
df = df.dropna(subset=["hair", "eye"])  # listwise deletion over the analysis columns
df["hair"] = df["hair"].cat.remove_unused_categories()
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, ["hair", "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
a, b = "hair", "eye"
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 = False
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(5000), seed=42)
    else:
        mc_p = csx.pd_chisq_mc(rows_code, cols_code, nr, nc, expected, int(5000), 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(5000):,} 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,
})

A significant table only says that something differs somewhere. The standardized residuals show where: cells beyond about ±2 stand out. A mosaic plot draws the same pattern.

07

Check your understanding

Checkpoint

Check yourself

A table has row total 60, column total 100 and grand total 200. What is the expected count in that cell?

Show the answer

Answer: 30

60 × 100 / 200 = 30.

Check yourself

How many degrees of freedom does a 3 × 4 table have?

Show the answer

Answer: 6

(3 − 1)(4 − 1) = 6.

Check yourself

You recruit 200 smokers and 200 non-smokers, then record whether each has a cough. Which framing fits?

Show the answer

Answer: a

You fixed the group sizes, so smoker prevalence isn't estimated from this sample. The test's arithmetic doesn't change, but the claim you can make does.

Check yourself

A 3 × 4 table has 24 people, with most expected counts below 5. Which test fits?

Show the answer

Answer: a

Fisher–Freeman–Halton extends Fisher's idea to any table size. It conditions on the margins and adds up the probabilities of tables no more likely than yours.

08

Do it in CodeSplash

In the app

Choose Rows and Columns, and set Question to Independence or Homogeneity. Test statistic switches between Pearson and G². For small tables, the exact test for R × C tables has its own dialog.

Python
import pandas as pd
from scipy import stats

df = pd.read_csv("hair_eye.csv")
table = pd.crosstab(df["hair"], df["eye"])
print(stats.chi2_contingency(table, correction=False))
print(stats.chi2_contingency(table, correction=False, lambda_="log-likelihood"))  # G
R
table <- margin.table(HairEyeColor, c(1, 2))
fit <- chisq.test(table, correct = FALSE)
fit
fit$stdres

Notebook exercise · ~10 min

A chi-square test on a two-by-two table

Build the admissions table, find an expected count, and compute Pearson's chi-square without the continuity correction both libraries apply by default.

  1. An expected count

    Under independence, a cell's expected count is its row total times its column total, divided by the grand total. Store the expected number of admitted men in expected_men_admitted.

    Show a solution
    Python
    expected_men_admitted = table.loc["Male"].sum() * table["Admitted"].sum() / table.to_numpy().sum()
    R
    expected_men_admitted <- sum(table["Male", ]) * sum(table[, "Admitted"]) / sum(table)
  2. Pearson's chi-square

    Store Pearson's chi-square statistic for the table without the continuity correction in chi2.

    Show a solution
    Python
    chi2 = stats.chi2_contingency(table, correction=False).statistic
    R
    chi2 <- unname(chisq.test(table, correct = FALSE)$statistic)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

09

Recap

Recap
  • Expected counts come from the margins; X2X^2 measures the gap between observed and expected.
  • Independence and homogeneity share the arithmetic but make different claims.
  • Report Cramér's V and look at residuals. A p-value alone says neither how strong nor where.

Concepts in this lesson