🔗 Module 3: Chi-Square Test of Independence

Testing Relationships Between Two Categorical Variables

Working guidelines

📚 Learning Objectives

By the end of this module, you will be able to:

🔗 What Does "Independence" Mean?

Two variables are independent when knowing the value of one variable tells you nothing about the other.

✅ Independent Variables

Example: Coin flip outcome and dice roll

Knowing you flipped heads tells you NOTHING about what number the die will show.

In research: "Treatment response is independent of sex" means males and females respond equally.

❌ Associated/Dependent Variables

Example: Species and habitat preference

Knowing the species DOES tell you about likely habitat (e.g., fish prefer water!).

In research: "Diagnosis is associated with treatment type" means different diagnoses get different treatments.

Chi-square test of independence asks:
"Are these two categorical variables related, or are they independent?"

📊 Understanding Contingency Tables

A contingency table (also called a cross-tabulation or crosstab) displays frequencies for two categorical variables simultaneously.

Example: Treatment Response by Sex

Research Question: Is treatment response independent of patient sex?

Treatment Response Row Total
Sex Improved No Improvement
Male 45 15 60
Female 25 35 60
Column Total 70 50 120

Reading this table:

  • 45 males improved, 15 males did not improve
  • 25 females improved, 35 females did not improve
  • Total sample size (n) = 120
  • Row totals: Number in each sex category
  • Column totals: Number in each response category

Visual pattern: Males seem more likely to improve (75%) than females (42%). Is this difference statistically significant?

🧮 Calculating Expected Frequencies

Under the null hypothesis (independence), we calculate what frequencies we'd EXPECT if the variables were truly unrelated.

Expected Frequency Formula

Expected = (Row Total × Column Total) / Grand Total

For each cell in the contingency table

📐 Calculate Expected Frequencies

Using the treatment response example:

Improved No Improvement
Male (n=60) Observed: 45
Expected: (60 × 70) / 120 = 35
Observed: 15
Expected: (60 × 50) / 120 = 25
Female (n=60) Observed: 25
Expected: (60 × 70) / 120 = 35
Observed: 35
Expected: (60 × 50) / 120 = 25

Key insight: If sex and response were independent, we'd expect equal success rates for males and females. The expected values reflect the OVERALL success rate (70/120 = 58%) applied to each group.

✍️ Your turn

Question 1: The table above works out the Male/Improved cell. Do the Female / No Improvement cell yourself, the same way — show the row total, the column total, the grand total, and the result.

Question 2: Every expected count in this table came out to 25 or 35 — never a fraction. That is a coincidence of these particular margins. Why is it fine for an expected count to be a non-whole number like 26.67, when you cannot observe 26.67 people?

💻 Running Chi-Square Test of Independence in R

1Create the Contingency Table

# Method 1: Enter data as a matrix data <- matrix(c(45, 15, 25, 35), nrow = 2, byrow = TRUE) rownames(data) <- c("Male", "Female") colnames(data) <- c("Improved", "No Improvement") # View the table data # Method 2: If you have raw data # data <- table(sex, response)

2Run the Chi-Square Test

# Simple test result <- chisq.test(data) result # To see expected frequencies result$expected # To see standardized residuals (more on this soon!) result$stdres

3Interpret the Output

Pearson's Chi-squared test with Yates' continuity correction data: data X-squared = 12.377, df = 1, p-value = 0.0004346

What this tells you:

  • X-squared = 12.377: Chi-square statistic
  • df = 1: (rows - 1) × (columns - 1) = (2-1) × (2-1) = 1
  • p-value = 0.0004346: Extremely strong evidence against independence
  • Yates' correction: Applied automatically for 2×2 tables (makes test more conservative)

Conclusion: We reject H₀. Treatment response is NOT independent of sex (p < .001). Males show significantly higher improvement rates than females.

✍️ Your turn

Question 3: Run all three blocks above. Does your X-squared match ours to the digit?

Question 4: "Treatment response is not independent of sex" is a statistical statement. Say what it means about these patients, in a sentence a non-statistician would understand — without using the word "independent."

📊 Seeing the Association

The test gives you one number. A plot shows you the pattern that produced it. This is ggplot2 from Chapter 8 — and because you already have counts, you want geom_col().

library(ggplot2) # ggplot2 wants one row per bar, not a matrix resp <- data.frame( sex = rep(c("Male", "Female"), each = 2), response = rep(c("Improved", "No Improvement"), times = 2), count = c(45, 15, 25, 35) ) # counts side by side ggplot(resp, aes(x = sex, y = count, fill = response)) + geom_col(position = "dodge") + labs(title = "Treatment response by sex", x = NULL, y = "Patients", fill = NULL) + theme_classic() # proportions within each group -- usually the clearer picture for # a test of independence, since it removes differences in group size ggplot(resp, aes(x = sex, y = count, fill = response)) + geom_col(position = "fill") + labs(title = "Treatment response by sex (proportions)", x = NULL, y = "Proportion", fill = NULL) + theme_classic()

✍️ Your turn

Question 5: Make both plots. Independence would mean the two bars split the same way in both groups. Looking at the proportion plot, how far from that is this table?

🔢 Degrees of Freedom for Test of Independence

df = (r - 1) × (c - 1)

r = number of rows
c = number of columns

Examples:

Table Size Calculation df
2 × 2 (2-1) × (2-1) 1
2 × 3 (2-1) × (3-1) 2
3 × 3 (3-1) × (3-1) 4
4 × 3 (4-1) × (3-1) 6

⚠️ Why (r-1) × (c-1)?

Once you know frequencies in (r-1) rows and (c-1) columns, plus all the marginal totals, the remaining cells are determined. This creates constraints on the data, reducing degrees of freedom.

🎯 Practice Problem 1: Species and Habitat

Research Question: Is habitat preference independent of species?

Data: Three species observed in two habitat types

Habitat Total
Species Forest Grassland
Species A 35 15 50
Species B 20 30 50
Species C 25 25 50
Total 80 70 150
# Create the table habitat_data <- matrix(c(35, 15, 20, 30, 25, 25), nrow = 3, byrow = TRUE) rownames(habitat_data) <- c("Species A", "Species B", "Species C") colnames(habitat_data) <- c("Forest", "Grassland") # Run test result <- chisq.test(habitat_data) result # Check expected frequencies result$expected

🔮 Predict first

Question 6: Species C splits 25/25 — dead even. Species A leans to forest, Species B to grassland. Before revealing the output: significant or not, and which species do you expect to contribute most to the chi-square?

🔍 Standardized Residuals: Finding the Pattern

When Chi-square is significant, the next question is: "WHICH cells are driving the effect?"

Standardized residuals tell you how far each cell deviates from expectation, in standard deviation units.

Standardized Residual = (Observed - Expected) / √Expected

Interpretation guidelines:

# Get standardized residuals result$stdres

Read the table directly — this is exactly what Chapter 21 does. A residual table for a 2 × 2 has only four numbers in it, and a plot of four numbers is not clearer than the four numbers.

Example: Treatment Response Residuals

Improved No Improvement Male 3.70 -3.70 Female -3.70 3.70

Interpretation:

  • Male/Improved: residual = +3.70 → Males improved MORE than expected
  • Male/No Improvement: residual = -3.70 → Males had FEWER non-improvements than expected
  • Female cells: Opposite pattern - fewer improvements, more non-improvements than expected

All |residuals| > 2, confirming that ALL cells contribute to the significant chi-square!

✍️ Your turn

Question 7: Notice that all four residuals have the same magnitude, 3.70, and only their signs differ. That is not a coincidence — it happens for every 2 × 2 table. Why? (Hint: if you know one cell and all four margins, how many of the other cells are still free to vary?)

Question 8: Now go back to your habitat table from Practice Problem 1 and run result$stdres on it. That one is 3 × 2, so the residuals are not all the same size. Which cell has the largest absolute residual, and what does that cell tell you about that species?

📏 Effect Size: Cramér's V

Chi-square tells you IF variables are related, but not HOW STRONG the relationship is. That's where effect size comes in!

Cramér's V measures the strength of association, ranging from 0 (no association) to 1 (perfect association).

V = √[χ² / (n × (k - 1))]

k = smaller of (number of rows, number of columns)
n = total sample size

Interpretation guidelines (for df = 1):

Cramér's V Interpretation
0.00 - 0.10 Negligible association
0.10 - 0.30 Weak association
0.30 - 0.50 Moderate association
> 0.50 Strong association
# Cramér's V comes from the vcd package (Chapter 21) library(vcd) assocstats(data)

What R prints for the treatment table:

X^2 df P(> X^2) Likelihood Ratio 14.023 1 0.00018059 Pearson 13.714 1 0.00021283 Phi-Coefficient : 0.338 Contingency Coeff.: 0.32 Cramer's V : 0.338

⚠️ Read the two chi-squares carefully

Look at what assocstats() just printed: Pearson = 13.714. But earlier on this page, chisq.test() reported X-squared = 12.377 for the same table. Neither is a mistake.

chisq.test() applies Yates' continuity correction by default on a 2 × 2 table; assocstats() computes Cramér's V from the uncorrected Pearson statistic. So the V you get depends on which statistic you build it from:

  • From the uncorrected 13.714 (what assocstats() reports): V = 0.338
  • From the Yates-corrected 12.377: V = 0.321

Both are defensible, and here both land in the same "moderate" band — but do not report the χ² from one and the V from the other without saying so. Chapter 21 makes the same point. The simplest honest habit: cite assocstats() for V and say you are doing that.

✍️ Your turn

Question 9: You now have two defensible values for the same effect size: 0.338 and 0.321. Pick one to report, and write the sentence you would actually put in a results section — including which chi-square it came from.

You can also compute V by hand from whichever χ² you have chosen:

# Manual calculation -- note WHICH chi-square goes in result <- chisq.test(data, correct = FALSE) # uncorrected, to match assocstats() chi_sq <- result$statistic n <- sum(data) k <- min(nrow(data), ncol(data)) V <- sqrt(chi_sq / (n * (k - 1))) V

Before you submit

Grading: Credit/no-credit, not scored for correctness — but credit requires a genuine attempt; blank or clearly-unattempted answers earn no credit. Work through it with your partner and say what you actually think; a wrong idea you reasoned your way to is worth more here than a right one you copied.

How to submit

  1. Click Save progress.
  2. Print: Ctrl+P (Windows) or Cmd+P (Mac).
  3. Choose "Save as PDF".
  4. Save as chisq3_lastname1_lastname2.pdf and upload to the course site.