Testing Relationships Between Two Categorical Variables
By the end of this module, you will be able to:
Two variables are independent when knowing the value of one variable tells you nothing about the other.
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.
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?"
A contingency table (also called a cross-tabulation or crosstab) displays frequencies for two categorical variables simultaneously.
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:
Visual pattern: Males seem more likely to improve (75%) than females (42%). Is this difference statistically significant?
Under the null hypothesis (independence), we calculate what frequencies we'd EXPECT if the variables were truly unrelated.
For each cell in the contingency table
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.
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?
Step-by-step for Male/Improved cell:
Interpretation: If there's no relationship between sex and improvement, we'd expect 35 of the 60 males to improve (the same proportion as in the overall sample).
# 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)
# Simple test
result <- chisq.test(data)
result
# To see expected frequencies
result$expected
# To see standardized residuals (more on this soon!)
result$stdres
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:
Conclusion: We reject H₀. Treatment response is NOT independent of sex (p < .001). Males show significantly higher improvement rates than females.
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."
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()
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?
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 |
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.
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
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?
Pearson's Chi-squared test
data: habitat_data
X-squared = 9.375, df = 2, p-value = 0.00921
Expected Frequencies:
| Forest | Grassland | |
|---|---|---|
| Species A | 26.67 | 23.33 |
| Species B | 26.67 | 23.33 |
| Species C | 26.67 | 23.33 |
Interpretation: χ²(2) = 9.38, p = .009. We reject H₀. Habitat preference is NOT independent of species. Looking at the data: Species A prefers forest (70%), Species B prefers grassland (60%), and Species C shows no preference (50/50).
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.
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.
Improved No Improvement
Male 3.70 -3.70
Female -3.70 3.70
Interpretation:
All |residuals| > 2, confirming that ALL cells contribute to the significant chi-square!
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?
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).
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
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:
assocstats() reports): V = 0.338Both 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.
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
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.
chisq3_lastname1_lastname2.pdf and upload to the course site.