Optional. Nothing in Module 3 assumes this page — it is the fourth template, for the one question shape the three main templates cannot answer: when both of your variables are categorical.
The t-test, ANOVA and regression on the Module 3 page all involve at least one continuous variable. But plenty of research questions relate two categories: does income band relate to whether a child feels safe in their neighbourhood? Do boys and girls differ in how curious they are about alcohol? For those, you reach for a chi-squared (χ²) test of independence, which asks whether the two category systems are related or independent.
It follows the same template shape as the others — clean, visualise, check the assumption, test, effect size, visualise the result — so if you have read one of the Module 3 templates this will feel familiar.
library(dplyr)
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
library(ggplot2)# tidyr is used below as tidyr::drop_na() and tidyr::pivot_wider()# (install it with install.packages("tidyr") if you need to)data <-readRDS("data/data.RDS")
The question
Is household income related to whether a child feels their neighbourhood is safe? Two categorical variables:
ab_g_dyn__cohort_income__hhold__3lvl — household income in three bands
fc_y_nsc__ns_003 — the youth’s response to a neighbourhood-safety item, on a five-point agree/disagree scale
Clean
Two wrinkles here that the continuous templates did not have. First, both variables carry the special codes 777 (decline to answer) and 999 (don’t know) — these are not points on the scale, so we drop them rather than let them masquerade as responses. Second, a five-point scale crossed with three income bands makes fifteen cells, and many will be nearly empty; we collapse the safety item to three categories so the cells are not too sparse for the test.
clean <- data |>select( participant_id, session_id,family_id = ab_g_stc__design_id__fam,income = ab_g_dyn__cohort_income__hhold__3lvl,safety = fc_y_nsc__ns_003 ) |>filter(session_id =="ses-00A") |># baseline onlyfilter(!income %in%c(777, 999), # drop "decline" / "don't know"!safety %in%c(777, 999)) |>mutate(income =case_when( income ==1~"< 50k", income ==2~"50k to 100k", income ==3~"> 100k",.default =NA ) |>factor(levels =c("< 50k", "50k to 100k", "> 100k")),# collapse the 5-point item into 3 so no cell is too sparsesafety =case_when( safety %in%c(1, 2) ~"Disagree", safety ==3~"Neutral", safety %in%c(4, 5) ~"Agree",.default =NA ) |>factor(levels =c("Disagree", "Neutral", "Agree")) ) |> tidyr::drop_na(family_id, income, safety)
As on the main page, we keep one child per family so siblings are not counted as independent observations:
Chi-squared’s main requirement is that expected counts are not too small — the usual rule is that every expected count should be at least 5. The test stores the expected counts, so we fit it once and inspect them.
Notice the warning R prints. Because most children feel safe, the Disagree column is thin, and one of these expected counts dips just below 5 — so R cautions that the chi-squared approximation may be incorrect. That warning is the assumption check doing its job. With the counts this close to the threshold and the association this strong (see the p-value below), the result still stands, but the clean remedies are to collapse further — fold Disagree and Neutral into a single not-agree category — or to switch to Fisher’s exact test, fisher.test(clean_no_sibs$income, clean_no_sibs$safety), which makes no large-sample approximation.
Warning in chisq.test(clean_no_sibs$income, clean_no_sibs$safety): Chi-squared
approximation may be incorrect
chi_result
Pearson's Chi-squared test
data: clean_no_sibs$income and clean_no_sibs$safety
X-squared = 24.647, df = 4, p-value = 5.924e-05
Read it as: X-squared is the test statistic, df the degrees of freedom (rows − 1) × (columns − 1), and p-value whether to reject the null hypothesis that income and perceived safety are independent. A p-value below 0.05 says they are related.
Effect size: Cramér’s V
As always, significance is not size. Cramér’s V rescales the chi-squared statistic to run from 0 (no association) to 1 (perfect association), so it is comparable across tables. A rough guide for a table with three levels on the smaller side: 0.1 small, 0.3 medium, 0.5 large.
A grouped bar chart of the row proportions shows the association directly: the taller the “Agree” bar climbs as income rises, the stronger the relationship.
plot_df <- clean_no_sibs |>count(income, safety) |>group_by(income) |>mutate(prop = n /sum(n)) |>ungroup()ggplot(plot_df, aes(x = income, y = prop, fill = safety)) +geom_col(position ="dodge", alpha =0.85) +labs(title ="Perceived neighbourhood safety by household income",x ="Household income", y ="Proportion within income band", fill ="Feels safe?" ) +theme_minimal()
Figure 1: Perceived neighbourhood safety by household income
In short
The chi-squared test of independence is the categorical counterpart to the tests on the main page:
Build a contingency table of the two categorical variables.
Check the expected counts are all at least 5 — collapse categories or use fisher.test() if not.
Run chisq.test() and read the p-value.
Report Cramér’s V as the effect size, and show the pattern with a grouped bar chart.