Skip to main content

Deep-dive · Chi-squared Tests

Optional companion to Module 3

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 only
  filter(!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 sparse
    safety = 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:

set.seed(1996)
clean_no_sibs <- clean |>
  group_by(family_id) |>
  slice_sample(n = 1) |>
  ungroup()

The contingency table

A chi-squared test runs on a cross-tabulation — a grid of counts, one cell per combination of the two variables. This table is the data for the test.

counts <- clean_no_sibs |>
  count(income, safety)

counts |>
  tidyr::pivot_wider(names_from = safety, values_from = n)  # long counts -> a grid
# A tibble: 3 × 4
  income      Disagree Neutral Agree
  <fct>          <int>   <int> <int>
1 < 50k             11      15    47
2 50k to 100k        4      15    52
3 > 100k             4      26   179

Adding row proportions makes the pattern easier to see — what share of each income band agrees their neighbourhood is safe:

counts |>
  group_by(income) |>
  mutate(prop = round(n / sum(n), 2)) |>  # proportions within each income row
  ungroup() |>
  select(income, safety, prop) |>
  tidyr::pivot_wider(names_from = safety, values_from = prop)
# A tibble: 3 × 4
  income      Disagree Neutral Agree
  <fct>          <dbl>   <dbl> <dbl>
1 < 50k           0.15    0.21  0.64
2 50k to 100k     0.06    0.21  0.73
3 > 100k          0.02    0.12  0.86

Check the assumption

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.

chi_check <- chisq.test(clean_no_sibs$income, clean_no_sibs$safety)
Warning in chisq.test(clean_no_sibs$income, clean_no_sibs$safety): Chi-squared
approximation may be incorrect
chi_check$expected  # all of these should be >= 5
                    clean_no_sibs$safety
clean_no_sibs$income  Disagree  Neutral     Agree
         < 50k        3.929178 11.58074  57.49008
         50k to 100k  3.821530 11.26346  55.91501
         > 100k      11.249292 33.15581 164.59490

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.

Run the test

chi_result <- chisq.test(clean_no_sibs$income, clean_no_sibs$safety)
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.

n <- nrow(clean_no_sibs)
k <- min(n_distinct(clean_no_sibs$income), n_distinct(clean_no_sibs$safety))  # smaller dimension
cramers_v <- sqrt(as.numeric(chi_result$statistic) / (n * (k - 1)))
cat("Cramér's V:", round(cramers_v, 3), "\n")
Cramér's V: 0.187 

Visualise the result

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()
Grouped bar chart of the proportion of children who disagree, are neutral, or agree that their neighbourhood is safe, within each of three income bands; the 'agree' proportion rises with income.
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.

Back to Module 3, or the downloadable R_Template_chi.square.R to run this on your own variables.