BIOSTATISTICS • CATEGORICAL DATA ANALYSIS

Chi-Square Test of Independence

A foundational nonparametric test for determining whether two categorical variables are statistically associated in a population.

Historical Context & Motivation

The need to determine whether two categorical variables are related — for instance, whether a treatment group and a disease outcome are statistically associated — has been a central concern of biostatistics since its earliest days. Before the development of formal hypothesis testing procedures for categorical data, researchers relied on subjective judgment and graphical comparisons to assess whether patterns in contingency tables reflected genuine associations or arose merely from sampling variability. The chi-square test of independence emerged at the turn of the twentieth century as the first rigorous, widely applicable method for answering this question, and it remains one of the most commonly used statistical procedures in the biomedical and social sciences today.

1900
Pearson's Chi-Square Statistic
Karl Pearson published his landmark paper introducing the χ² goodness-of-fit statistic, providing a general framework for comparing observed and expected frequencies. This work laid the mathematical foundation for all subsequent chi-square methods.
1922
Fisher's Refinements
Ronald A. Fisher clarified the correct degrees of freedom for contingency tables and demonstrated that the chi-square approximation improves as sample sizes grow, formalizing the large-sample theory that underpins the test.
1934
Fisher's Exact Test as an Alternative
Fisher introduced an exact test for 2 × 2 tables, motivating careful attention to the conditions under which the chi-square approximation is adequate — particularly the minimum expected cell frequency requirements still discussed in textbooks today.
1949
Yates' Continuity Correction
Frank Yates proposed a continuity correction for 2 × 2 tables to improve the chi-square approximation when sample sizes are moderate, though its routine use has since been debated in the statistical literature.
1970s–Present
Computational Era & Extensions
With digital computing, exact permutation tests became feasible for larger tables, and log-linear models generalized the chi-square framework to multi-way contingency tables, solidifying chi-square methods as foundational to modern categorical data analysis.

The core question the chi-square test of independence addresses is deceptively simple: are two categorical variables independent, or is there a statistically significant association between them? In biostatistics, this question arises constantly — does smoking status relate to lung cancer diagnosis? Is a genetic marker associated with drug response? Does vaccination status predict infection outcome? Understanding how to construct, execute, and interpret this test is an essential skill in any data analyst's or clinical researcher's toolkit.

Core Principles & Definitions

The chi-square test of independence operates on data arranged in a contingency table (also called a cross-tabulation), where the rows represent the categories of one variable and the columns represent the categories of another. The test compares the observed cell frequencies to the frequencies one would expect if the two variables were entirely independent. A large discrepancy between observed and expected counts provides evidence against the null hypothesis of independence. Before diving into the mathematics, it is important to understand the foundational concepts that give the test its structure and validity.

1

Null & Alternative Hypotheses

H₀: The two categorical variables are independent — knowing the category of one variable provides no information about the other. H₁: The variables are not independent; an association exists in the population.
2

Observed vs. Expected Frequencies

Observed frequencies (O) are the actual counts in each cell. Expected frequencies (E) are the counts predicted under independence, computed from the marginal totals.
3

Degrees of Freedom

For an r × c table, df = (r − 1)(c − 1). The degrees of freedom determine the specific chi-square distribution used to obtain the p-value and reflect the number of cells free to vary once marginal totals are fixed.
4

Assumptions & Conditions

The data must consist of independent random observations. Each observation belongs to exactly one cell. Expected frequencies should generally be ≥ 5 in at least 80% of cells (and no cell below 1) for the χ² approximation to be reliable.
5

The χ² Distribution

Under H₀, the test statistic follows an approximate chi-square distribution with (r − 1)(c − 1) degrees of freedom. This right-skewed distribution converges to the true sampling distribution as N grows large.
KEY TAKEAWAY
Think of the chi-square test as a discrepancy detector for a contingency table. Imagine you have a perfectly balanced roulette wheel (independence) and you spin it many times, recording outcomes in a grid. The expected frequencies are what a fair wheel predicts. The χ² statistic measures how far your actual results deviate from that fair-wheel prediction — a small value means the data look consistent with independence, while a large value signals that something systematic is going on, just as a consistently biased roulette wheel would eventually reveal itself through persistent deviations from the expected distribution of outcomes.

Visual Explanation: Observed vs. Expected Frequencies

The following diagram illustrates the conceptual logic of the chi-square test of independence using a 2 × 2 contingency table. On the left, you see the observed frequency table — the actual data collected from a study. On the right, the expected frequency table shows what the cell counts would be if the two variables were perfectly independent, computed from the marginal totals. The arrows between the tables represent the comparison that generates the χ² test statistic: each cell's contribution is proportional to the squared difference between its observed and expected values, divided by the expected value.

A 2 × 2 contingency table comparing exposure status and disease outcome. The observed table (left) records actual data; the expected table (right) shows the counts predicted under independence. Each cell's contribution to χ² is shown at the bottom.

The diagram above reveals the core mechanics of the test. Under independence, the probability of falling into any given cell equals the product of the two corresponding marginal probabilities — a direct consequence of the multiplicative rule for independent events. When the observed counts deviate substantially from these expected values, the χ² statistic grows, and the p-value shrinks. Notice how in this example the exposed group has a higher disease rate (30%) than the unexposed group (20%), producing a modest χ² of 2.67. Whether this is statistically significant depends on the critical value from the χ² distribution with df = (2 − 1)(2 − 1) = 1.

Mathematical Framework

The mathematical formulation of the chi-square test of independence proceeds from the null hypothesis that two categorical variables are independent. Under this assumption, the joint probability of any cell in an r × c table equals the product of its row and column marginal probabilities. The test statistic quantifies the aggregate discrepancy between observed and expected cell counts, and its sampling distribution under H₀ is approximately chi-square when the sample size is sufficiently large.

EXPECTED FREQUENCY
E_ij = (R_i × C_j) / N
Where Eij is the expected frequency in row i, column j; Ri is the total for row i; Cj is the total for column j; and N is the grand total of all observations.
PEARSON'S CHI-SQUARE STATISTIC
χ² = Σ Σ (O_ij − E_ij)² / E_ij
The double summation runs over all r rows and c columns. Oij denotes the observed count in cell (i, j). Each cell contributes a non-negative term; cells with large deviations from expected values dominate the sum.
DEGREES OF FREEDOM
df = (r − 1)(c − 1)
Where r is the number of rows and c is the number of columns. For a 2 × 2 table, df = 1; for a 3 × 4 table, df = 6. The degrees of freedom reflect the number of independent comparisons between observed and expected frequencies.

The derivation of the chi-square approximation rests on the multinomial distribution. Under the null hypothesis, the vector of cell counts follows a multinomial distribution with cell probabilities equal to the products of marginal probabilities. By the multivariate central limit theorem, the standardized cell counts are asymptotically jointly normal, and the quadratic form in the test statistic converges to a chi-square distribution with (r − 1)(c − 1) degrees of freedom. The loss of degrees of freedom arises because (r − 1) + (c − 1) parameters (the marginal probabilities, minus the constraints that they sum to 1) are estimated from the data.

P-VALUE COMPUTATION
p = P(χ²_df ≥ χ²_obs)
The p-value is the probability of obtaining a chi-square statistic at least as extreme as the observed value, under the null hypothesis. Because any departure from independence (in any direction) inflates χ², the test is always right-tailed.

Assumptions, Validity Conditions & Decision Process

The chi-square approximation is not universally applicable; its validity depends on several conditions related to sampling design and expected cell frequencies. Violating these assumptions can inflate the Type I error rate or reduce the power of the test. The following diagram presents a decision flowchart for determining whether the standard Pearson chi-square test is appropriate for a given dataset, or whether alternative methods should be considered.

Decision flowchart for selecting the appropriate test. The chi-square test of independence requires two categorical variables, independent observations, and adequate expected cell frequencies. When conditions are violated, Fisher's exact test or McNemar's test may be more appropriate.
  • Random sampling: Each observation must be independently drawn from the population. Clustered or matched-pairs data violate this assumption and require specialized methods (e.g., McNemar's test, generalized estimating equations).
  • Mutually exclusive categories: Each observation falls into exactly one cell. If subjects can belong to multiple categories, the data do not form a proper contingency table.
  • Sufficient expected frequencies: The rule of thumb is that all expected frequencies should be ≥ 5. Cochran's guideline relaxes this: no more than 20% of cells may have E < 5, and no cell may have E < 1. When these conditions fail, Fisher's exact test is preferred.
  • Fixed or large sample size: The chi-square approximation improves with larger N. With very small samples, the discrete nature of count data makes the continuous χ² distribution a poor fit.

Worked Example: Smoking and Respiratory Disease

A clinical epidemiologist surveys 400 adults and classifies each by smoking status (Smoker, Non-smoker) and presence of chronic respiratory disease (Yes, No). The resulting 2 × 2 contingency table is shown below. We will carry out a chi-square test of independence at the α = 0.05 significance level to determine whether there is a statistically significant association between smoking and respiratory disease.

Observed frequencies: Smoking status vs. respiratory disease
Disease: YesDisease: NoRow Total
Smoker6090150
Non-smoker40210250
Column Total100300400
Chi-Square Test of Independence: Smoking & Respiratory Disease
1
Step 1 — State HypothesesH₀: Smoking status and respiratory disease are independent. H₁: Smoking status and respiratory disease are not independent (an association exists). We set α = 0.05.
2
Step 2 — Compute Expected FrequenciesUsing Eij = (Ri × Cj) / N: E(Smoker, Yes) = (150 × 100) / 400 = 37.5; E(Smoker, No) = (150 × 300) / 400 = 112.5; E(Non-smoker, Yes) = (250 × 100) / 400 = 62.5; E(Non-smoker, No) = (250 × 300) / 400 = 187.5. All expected frequencies exceed 5, so the chi-square approximation is valid.
E = {37.5, 112.5, 62.5, 187.5}
3
Step 3 — Compute the χ² Statisticχ² = (60 − 37.5)² / 37.5 + (90 − 112.5)² / 112.5 + (40 − 62.5)² / 62.5 + (210 − 187.5)² / 187.5 = (22.5)² / 37.5 + (−22.5)² / 112.5 + (−22.5)² / 62.5 + (22.5)² / 187.5 = 506.25 / 37.5 + 506.25 / 112.5 + 506.25 / 62.5 + 506.25 / 187.5 = 13.50 + 4.50 + 8.10 + 2.70
χ² = 28.80
4
Step 4 — Determine Degrees of Freedomdf = (r − 1)(c − 1) = (2 − 1)(2 − 1) = 1.
df = 1
5
Step 5 — Find the p-value and Make a DecisionThe critical value for χ² with df = 1 at α = 0.05 is 3.841. Our observed χ² = 28.80 greatly exceeds this threshold. The corresponding p-value is p < 0.0001. Since p < 0.05, we reject the null hypothesis.
Reject H₀: There is a statistically significant association between smoking status and respiratory disease (χ² = 28.80, df = 1, p < 0.0001).
6
Step 6 — Interpret & Report Effect SizeTo quantify the strength of association, compute Cramér's V = √(χ² / (N × min(r − 1, c − 1))) = √(28.80 / (400 × 1)) = √0.072 ≈ 0.268. By conventional benchmarks (small ≈ 0.10, medium ≈ 0.30, large ≈ 0.50 for df* = 1), this represents a small-to-medium association. Smokers had a 40% disease rate compared with 16% among non-smokers.
Cramér's V ≈ 0.268 (small-to-medium effect)

Strengths, Limitations & Common Pitfalls

Comparative strengths and limitations of the chi-square test of independence
AspectStrengthsLimitations
Distributional AssumptionsNonparametric — no assumption about the shape of the underlying distribution of the variables.Requires sufficient expected cell frequencies (generally ≥ 5); inappropriate for very sparse tables.
GeneralityHandles any r × c table — not limited to 2 × 2. Works with nominal and ordinal variables alike.Does not exploit ordinal information; ordinal-specific tests (Mantel–Haenszel trend test) may be more powerful when order matters.
InterpretationSimple, well-understood test statistic and p-value; easily paired with Cramér's V for effect size.Detects association but not causation. A significant result does not indicate the direction or pattern of association in larger tables.
Sample Size SensitivityComputationally trivial; works well for large observational studies and clinical trials.With very large N, even trivially small associations become significant — always report effect size alongside the p-value.
Multiple ComparisonsCan be followed up with post-hoc residual analysis to identify which cells drive significance.An omnibus test — in r × c tables with many cells, a significant result requires additional analysis (e.g., standardized residuals) to locate the source of association.
KEY TAKEAWAY
The chi-square test tells you whether an association exists, not how strong it is or why it exists. Think of it like a smoke detector in a building: it alerts you that something is burning, but it cannot tell you whether the fire is in the kitchen or the basement, nor whether it is a grease fire or an electrical one. For the full picture, you need follow-up tools — effect size measures like Cramér's V or phi for magnitude, standardized residuals for localization, and study design considerations (randomization, confounding control) for causal inference.

Connection to Advanced Methods in Categorical Data Analysis

The Pearson chi-square test of independence serves as the entry point to a rich family of methods for analyzing categorical data. As research questions grow more complex — involving confounders, multiple response variables, or hierarchical data structures — more sophisticated tools become necessary. Understanding how the chi-square test relates to these advanced methods provides conceptual scaffolding for further study.

Relationship between the chi-square test of independence and advanced categorical data analysis methods
MethodRelationship to Chi-Square TestWhen to Use Instead
Fisher's Exact TestComputes the exact p-value from the hypergeometric distribution rather than relying on the χ² approximation.Small samples or sparse tables where expected cell counts fall below 5.
G-test (Likelihood Ratio)Uses G = 2 Σ O ln(O/E) instead of Σ(O−E)²/E. Asymptotically equivalent but decomposable in multi-way tables.Log-linear modeling contexts; preferred for hierarchical model selection.
Mantel–Haenszel TestPools evidence across strata (e.g., multiple study sites) while controlling for a confounding variable.Stratified 2 × 2 tables where confounding needs adjustment.
Logistic RegressionGeneralizes the 2 × 2 chi-square to multivariate settings; the Wald test of a single predictor in a saturated model is equivalent to the chi-square test.Multiple predictors, continuous covariates, or when odds ratios with confidence intervals are desired.
Log-Linear ModelsModel cell counts as a function of main effects and interactions; the test of the independence model vs. the saturated model yields the familiar χ².Three-way or higher-order contingency tables; exploring complex interaction patterns.

A particularly elegant connection exists between the chi-square test and logistic regression. In a 2 × 2 table with one binary predictor and one binary outcome, fitting a simple logistic regression model and testing whether the regression coefficient differs from zero yields a Wald statistic that equals the Pearson χ² (asymptotically). This correspondence reveals the chi-square test as a special case of the broader generalized linear model framework, which unifies many of the methods listed above under a common theoretical umbrella. As you progress in biostatistics, recognizing these connections will deepen your understanding of when and why each method is appropriate.

Practice Problems

PROBLEM 1CONCEPTUAL
A researcher conducts a chi-square test of independence on a 3 × 2 contingency table and obtains χ² = 0.42 with a p-value of 0.81. Explain what this result means in the context of the null and alternative hypotheses. Does this result prove that the two variables are independent?
PROBLEM 2BASIC CALCULATION
In a study of 200 patients, the following 2 × 2 table is observed: Treatment A with Recovery = 50, No Recovery = 30; Treatment B with Recovery = 60, No Recovery = 60. Compute all four expected cell frequencies and verify that each row and column sum matches the observed marginals.
PROBLEM 3INTERMEDIATE
Using the data from Problem 2 (Treatment A: 50 Recovery, 30 No Recovery; Treatment B: 60 Recovery, 60 No Recovery; N = 200), carry out the full chi-square test of independence at α = 0.05. Compute χ², state the degrees of freedom, determine whether to reject H₀, and calculate Cramér's V.
PROBLEM 4APPLIED
A geneticist cross-tabulates genotype (AA, Aa, aa) by phenotype (Affected, Unaffected) in a sample of 300 individuals, obtaining: AA—Affected: 10, AA—Unaffected: 90; Aa—Affected: 30, Aa—Unaffected: 70; aa—Affected: 50, aa—Unaffected: 50. Perform a chi-square test of independence at α = 0.01 and interpret the biological significance of the result.
PROBLEM 5CRITICAL THINKING
A large epidemiological study with N = 50,000 subjects finds a statistically significant chi-square test (χ² = 12.4, df = 1, p = 0.0004) for the association between coffee consumption (Yes/No) and a rare disease (Yes/No), but Cramér's V = 0.016. Critically evaluate this finding. What does it tell us about the relationship between statistical significance and practical significance? What additional analyses would you recommend, and why might the chi-square test be particularly misleading in this context?

Chi-Square Test of Independence — Summary

The chi-square test of independence evaluates whether two categorical variables are statistically associated by comparing observed cell frequencies in a contingency table to the expected frequencies predicted under the null hypothesis of independence. The test statistic χ² = Σ(O − E)² / E follows an approximate chi-square distribution with df = (r − 1)(c − 1) degrees of freedom when the sample is sufficiently large and all expected cell counts meet the minimum threshold.

Key assumptions include independent observations, mutually exclusive categories, and expected frequencies generally ≥ 5. When assumptions are violated, alternatives such as Fisher's exact test should be used. A significant χ² result indicates that an association exists but does not reveal its strength or direction — always supplement with effect size measures such as Cramér's V and standardized residuals to fully characterize the relationship between variables.

Varsity Tutors • Biostatistics • Chi-Square Test of Independence