The Chi-Square Test: Evaluating Categorical Patterns and Independence with Counts

Much of real-world data arrives not as continuous measurements like temperature or weight, but as categorical counts. A product team tracks whether users pick Plan A, Plan B, or Plan C across desktop and mobile devices; a geneticist checks whether observed phenotype frequencies match Mendelian ratios; a healthcare researcher asks whether treatment group and adverse-event severity are independent. When data are organized into frequencies across discrete categories, the chi-square ($\chi^2$) test provides a foundational statistical method for deciding whether observed counts diverge meaningfully from what would be expected under a baseline hypothesis.

Introduced by English statistician Karl Pearson in 1900, Pearson’s chi-square test remains one of the most widely taught and applied hypothesis tests in statistics, data science, social research, and quality assurance—largely because of its conceptual transparency and broad applicability to count tables.

Core Idea: Observed vs. Expected Frequencies

At the heart of every chi-square test is a comparison between two sets of counts across $k$ mutually exclusive categories or cells:

  • Observed Frequencies ($O_i$): The actual counts recorded in your sample.
  • Expected Frequencies ($E_i$): The counts you would expect to observe if the null hypothesis ($H_0$) were true.

Pearson’s chi-square statistic aggregates the squared differences between observed and expected counts, scaled by expected frequency so large cells do not automatically dominate small ones:

$$\chi^2 = \sum_{i=1}^{k} \frac{(O_i – E_i)^2}{E_i}$$

Why square the differences? Positive and negative discrepancies across cells would cancel out if summed directly; squaring ensures every deviation contributes positively to $\chi^2$. Dividing by $E_i$ expresses each discrepancy relative to expected cell size—a deviation of 10 counts means something very different when E = 200 than when E = 15. Larger $\chi^2$ values indicate greater departure from expected counts under $H_0$, producing smaller p-values when evaluated against the appropriate chi-square distribution with given degrees of freedom ($\text{df}$).

Three Main Flavors of the Chi-Square Test

Practitioners most commonly encounter three closely related chi-square tests, each tailored to a distinct question about categorical counts:

Chi-Square VariantNull Hypothesis (H0​)Expected Count FormulaDegrees of Freedom (df)
Goodness-of-Fit TestCategorical counts follow a specified theoretical or historical probability distribution ($p_1, p_2, \dots, p_k$).$E_i = N \cdot p_i$ (where $N = \sum O_i$)$k – 1$ (or $k – 1 – m$ if $m$ parameters are estimated from data)
Test of IndependenceTwo categorical variables in a contingency table are statistically independent (no association).$E_{rc} = \frac{(\text{Row } r \text{ Total}) \times (\text{Column } c \text{ Total})}{N}$$(r – 1)(c – 1)$ for an $r \times c$ table
Test of HomogeneityMultiple independent sub-populations share the same distribution across categories of a single variable.Same cell-wise formula as independence across group rows and outcome columns$(r – 1)(c – 1)$ for $r$ groups and $c$ categories

Notice how structurally similar the test of independence and the test of homogeneity are: both compute expected values from marginal totals on a two-way table, though their study designs differ (one sample cross-classified by two categorical variables versus multiple separate samples measured on one categorical outcome).

Assumptions and When to Use Alternatives

Like any parametric or asymptotic approximation, the chi-square test relies on key assumptions:

  1. Independent Observations: Each count should come from distinct, independent units—not repeated observations on the same subject over time or clustered groups (which inflate variance and distort test size).
  2. Mutually Exclusive Categories: Every observation falls into one and only one cell of the table.
  3. Sufficient Expected Cell Counts: Because the sampling distribution of $\sum (O_i – E_i)^2 / E_i$ is approximated by a continuous $\chi^2$ distribution, very small expected counts can make the approximation inaccurate. A classic rule of thumb is that expected counts should generally be at least 5 in most cells (and not near zero in tiny tables).

When expected counts are very small—especially in a $2 \times 2$ table—Fisher’s exact test computes exact probabilities directly from hypergeometric combinatorics rather than relying on large-sample approximation. And for $2 \times 2$ tables using the $\chi^2$ approximation, analysts sometimes apply Yates’ continuity correction, though some statisticians note it can be overly conservative; modern workflows often inspect exact tests or logistic regression when covariates are present.

Practical Example in R

In R, chisq.test() handles both goodness-of-fit vectors and two-way contingency tables cleanly, and lets you inspect expected counts and residuals:

R

# 1. Test of independence on a 2x3 contingency table
tbl <- matrix(
  c(48, 32, 20,
    30, 40, 30),
  nrow = 2,
  byrow = TRUE,
  dimnames = list(
    Platform = c("Desktop", "Mobile"),
    Plan = c("Basic", "Pro", "Enterprise")
  )
)

res <- chisq.test(tbl)
print(res)

# Inspect expected counts and Pearson residuals to see which cells drive chi-square
round(res$expected, 2)
round(res$residuals, 2)

Examining Pearson residuals, defined as $z_i = \frac{O_i – E_i}{\sqrt{E_i}}$, is particularly helpful after rejecting $H_0$: a significant omnibus $\chi^2$ tells you some discrepancy exists across the table, while cell residuals show which specific combinations contribute most.

Practical Pitfalls and Good Habits

  • Large Sample Sizes and Practical Significance: With tens of thousands of observations, even a tiny 1% shift in category proportions can yield a statistically significant p-value. Always report effect sizes (such as Cramér’s $V$ for contingency tables) alongside the test statistic and sample size so you judge real-world relevance, not just statistical significance.
  • Post-Hoc Multiple Comparisons: When a table has many rows or columns and you run follow-up pairwise tests, adjust for multiple testing so false positives do not creep in.
  • No Causal Claim from Association Alone: A significant chi-square test of independence in observational data indicates statistical association between two categorical variables, not necessarily causation—confounding variables may drive both.