This page is under active development. The content might change.
Designed for someone with intermediate knowledge of R and RStudio. The first two modules exist to prepare you for this one — if you are comfortable reading a file, wrangling it with dplyr and drawing a ggplot2 figure, you are ready.
Modules 1 and 2 asked what does the data look like? This module asks the next question: is a pattern we can see in the sample likely to be real in the population, or could it just be noise? That is the whole job of inferential statistics.
From description to inference
A descriptive statistic summarises the sample in front of you: baseline height averaged 1.55 m, boys were taller than girls by a couple of centimetres. An inferential statistic asks whether that gap would survive if you could measure every child in the country, not just the 500 in this file.
Three ideas carry the whole session:
The null hypothesis. We start by assuming there is no effect — no difference between groups, no relationship between variables — and ask how surprising our data would be if that were true.
The p-value. How surprising, exactly. A p-value below 0.05 is the usual (arbitrary, conventional) line for calling a result “statistically significant” and rejecting the null. It is not the probability the result is real, and a tiny p-value on a trivial effect is still a trivial effect.
The effect size. How big the effect is, on a scale that does not depend on sample size. A p-value tells you whether an effect is there; an effect size tells you whether it matters. Report both. Every template below does.
Which test you reach for depends entirely on the shape of your question — specifically, what kind of variables you are relating:
Your question
The variables
The test
Do two groups differ on a number?
1 categorical (2 levels) + 1 continuous
t-test
Do three or more groups differ on a number?
1 categorical (3+ levels) + 1 continuous
ANOVA
Does one number predict another?
2 continuous
linear regression
Are two categories related?
2 categorical
chi-squared
Most of this page is three worked templates — t-test, ANOVA and regression — that you can download, point at your own variables, and adapt into a poster-worthy analysis. The fourth, chi-squared, lives on its own deep-dive page.
Important
Module 3 is a prerequisite for Module 4, the hands-on project session. There you will take one of these templates and build it into a proto-poster — so the work you do here is the work you present there.
NoteBefore you start
Download the dataset and its dictionaries from the dataset page — data.RDS, data_dictionary.csv and data_dictionary_levels.csv — into your project’s data/ folder, next to abcd-synthetic.csv from Module 1.
The templates are the live materials for this session. Download whichever you need and open it in RStudio:
Every chunk on this page is drawn from those files, lightly adapted so it runs from your project root.
The data
We work on data/data.RDS, the same ABCD-shaped dataset as Module 2 — 500 participants across five annual visits, with coded variable names and a separate data dictionary. Two of its properties shape every analysis on this page:
It is longitudinal. The five rows belonging to one child are not five independent observations, and neither are two siblings from the same family. A hypothesis test assumes independent observations, so we have to engineer that independence ourselves (below).
About 27% of cells are missing, and the missingness is structured — never a uniform random sprinkle. Dropping incomplete rows is never free; it quietly changes who you are studying. We use complete cases here because it keeps the code readable, but we flag it as a choice, not a default.
0. Load libraries
Following the convention from Module 2, we load only the two workhorses — dplyr and ggplot2 — with library(). Every function from another package is written with its package name attached, like tidyr::drop_na() or car::leveneTest(), so you can always see at a glance where a function comes from.
library(dplyr) # data wrangling
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) # figures
You will also need these installed — install.packages(c("tidyr", "car", "moments", "lmtest")): tidyr for drop_na() and pivot_wider(), car for Levene’s test, moments for skewness and kurtosis, and lmtest for the Breusch-Pagan test.
Anatomy of a template
All three templates follow the same seven steps. Learn the shape once and every test on this page — and most you will meet later — becomes a matter of swapping in different variables:
Clean — pick your variables, keep the baseline visit, give the columns readable names, and decide what to do with missing data.
Visualise the raw variables, before any test.
Check assumptions — mainly normality and, where it applies, equal variances.
Engineer independence — keep one child per family so siblings do not count twice.
Run the test.
Compute an effect size.
Visualise the result.
The three templates differ only in steps 3, 5, 6 and 7 — exactly the steps that depend on your question. Steps 1, 2 and 4 are nearly identical every time.
Template 1 · Two groups: the t-test
The question: do boys and girls differ in height at baseline? One continuous outcome (height), one two-level grouping variable (sex). That is the signature of a t-test.
Clean
We pick five columns, keep only the baseline visit (ses-00A), rename the cryptic ABCD columns, recode sex from 1/2 to labels, and drop rows missing any of our variables.
data <-readRDS("data/data.RDS")clean <- data |>select( participant_id, session_id,family_id = ab_g_stc__design_id__fam, # needed for the independence stepsex = ab_g_stc__cohort_sex,height = ph_y_anthr__height_mean ) |>filter(session_id =="ses-00A") |># baseline only -- no longitudinal modelling heremutate(sex =case_when( # recode the codes... sex ==1~"Male", sex ==2~"Female",.default =NA ) |>factor(levels =c("Female", "Male")) # ...then make it a factor ) |> tidyr::drop_na(family_id, sex, height) # complete-case analysis (a choice, not a default)glimpse(clean)
Complete-case analysis throws away everyone with a gap. Because ABCD’s missingness is structured — see the dataset page — that can bias your result. Multiple imputation is the better tool, but it is well beyond this session; naming the trade-off is what matters here.
Visualise
Always look before you test.
ggplot(clean, aes(x = height, fill = sex)) +geom_histogram(binwidth =0.5, alpha =0.6, position ="identity") +facet_wrap(~sex) +labs(title ="Distribution of baseline height by sex", x ="Height", y ="Count") +theme_minimal()
Figure 1: Baseline height, split by sex
Check assumptions
Normality. The Shapiro-Wilk test asks whether a sample could have come from a normal distribution (p > 0.05 is reassuring). Skewness should sit roughly within ±2 and excess kurtosis within ±7. A Q-Q plot shows the same thing by eye — points hugging the line mean “normal.”
clean |>group_by(sex) |>summarise(shapiro_p =shapiro.test(height)$p.value, # p > 0.05 is reassuringskew = moments::skewness(height), # aim for roughly within +/- 2kurtosis = moments::kurtosis(height) # moments::kurtosis() centres a normal at 3 )
# A tibble: 2 × 4
sex shapiro_p skew kurtosis
<fct> <dbl> <dbl> <dbl>
1 Female 0.00636 0.373 2.79
2 Male 0.554 -0.188 2.84
TipYou will also see by()
Base R does the same per-group check with by() — it splits a vector by a grouping factor and applies a function to each piece. You will meet it in older scripts and other people’s code, so it is worth recognising:
by(clean$height, clean$sex, shapiro.test)
clean$sex: Female
Shapiro-Wilk normality test
data: dd[x, ]
W = 0.98476, p-value = 0.00636
------------------------------------------------------------
clean$sex: Male
Shapiro-Wilk normality test
data: dd[x, ]
W = 0.99451, p-value = 0.554
We use group_by() |> summarise() on this page because it returns a tidy table and folds skewness and kurtosis into the same call — but the two give the same Shapiro-Wilk result.
ggplot(clean, aes(sample = height, color = sex)) +stat_qq() +stat_qq_line() +labs(title ="Q-Q plot by sex") +theme_minimal()
Figure 2: Q-Q plot of height by sex
Equal variances. A standard t-test assumes the two groups have the same spread. Levene’s test checks it: p > 0.05 means equal variances are a fair assumption, so we can use var.equal = TRUE. If it failed, we would switch to Welch’s correction (var.equal = FALSE).
car::leveneTest(height ~ sex, data = clean)
Levene's Test for Homogeneity of Variance (center = median)
Df F value Pr(>F)
group 1 0.1679 0.6822
498
Engineer independence
Siblings share a family, so two children from one family are not independent observations. We keep a single, randomly chosen child per family. set.seed() makes that random choice reproducible — anyone running the code gets the same sample.
set.seed(1996) # any fixed number works; it just has to be the same every runclean_no_sibs <- clean |>group_by(family_id) |>slice_sample(n =1) |># one child per familyungroup()nrow(clean) -nrow(clean_no_sibs) # how many siblings were dropped
[1] 38
Run the t-test
t_result <-t.test(height ~ sex, data = clean_no_sibs, var.equal =TRUE)t_result
Two Sample t-test
data: height by sex
t = 2.6055, df = 460, p-value = 0.00947
alternative hypothesis: true difference in means between group Female and group Male is not equal to 0
95 percent confidence interval:
0.2503769 1.7869635
sample estimates:
mean in group Female mean in group Male
57.56245 56.54378
Read it as: t is the test statistic, df the degrees of freedom, p-value whether to reject the null of equal means, and the 95% CI the plausible range for the true difference. If the interval excludes zero, the groups differ.
Effect size: Cohen’s d
The p-value says whether the means differ; Cohen’s d says by how much, in standard-deviation units. Rough guide: 0.2 small, 0.5 medium, 0.8 large.
ggplot(clean_no_sibs, aes(x = sex, y = height, fill = sex)) +geom_boxplot(alpha =0.7, outlier.shape =16) +geom_jitter(width =0.1, alpha =0.4) +labs(title ="Baseline height by sex", x ="Sex", y ="Height") +theme_minimal() +theme(legend.position ="none")
Figure 3: Baseline height by sex
Template 2 · Three or more groups: ANOVA
The question: does baseline height differ across parental-education groups? Now the grouping variable has five levels, so a t-test will not do — we need a one-way ANOVA, which generalises the t-test to any number of groups.
The cleaning and independence steps are the same shape as the t-test, so the prose is lighter here — watch the pattern repeat.
Clean
clean <- data |>select( participant_id, session_id,family_id = ab_g_stc__design_id__fam,parental_edu = ab_g_dyn__cohort_edu__cgs, # five ordered levelsheight = ph_y_anthr__height_mean ) |>filter(session_id =="ses-00A") |>mutate(# case_when() recodes; factor(levels = …) fixes the order for plots and post-hoc testsparental_edu =case_when( parental_edu ==1~"less_than_HS", parental_edu ==2~"HS_diploma", parental_edu ==3~"some_college", parental_edu ==4~"bachelor_degree", parental_edu ==5~"graduate_degree",.default =NA ) |>factor(levels =c("less_than_HS", "HS_diploma", "some_college","bachelor_degree", "graduate_degree")) ) |> tidyr::drop_na(family_id, parental_edu, height)glimpse(clean)
ggplot(clean, aes(x = height, fill = parental_edu)) +geom_histogram(binwidth =0.5, alpha =0.6, position ="identity") +facet_wrap(~parental_edu) +labs(title ="Distribution of height by parental education", x ="Height", y ="Count") +theme_minimal() +theme(legend.position ="none")
Figure 4: Baseline height across parental-education groups
Check assumptions
Same normality battery as before, now within each of the five groups, plus Levene’s test across all five. ANOVA is fairly robust to mild non-normality when groups are reasonably sized.
Df Sum Sq Mean Sq F value Pr(>F)
parental_edu 4 38 9.577 0.542 0.705
Residuals 449 7927 17.655
The Pr(>F) column is the p-value. A significant ANOVA tells you that at least one group differs — but not which one. (If Levene’s test had failed, you would swap aov() for oneway.test(height ~ parental_edu, var.equal = FALSE), Welch’s ANOVA.)
Post-hoc: which groups differ?
Tukey’s HSD compares every pair of groups while correcting for the many comparisons, so you do not inflate your false-positive rate. Run it only if the ANOVA was significant.
ggplot(clean_no_sibs, aes(x = parental_edu, y = height, fill = parental_edu)) +geom_boxplot(alpha =0.7, outlier.shape =16) +geom_jitter(width =0.1, alpha =0.4) +labs(title ="Baseline height across parental-education groups",x ="Parental education", y ="Height") +theme_minimal() +theme(legend.position ="none", axis.text.x =element_text(angle =20, hjust =1))
Figure 6: Baseline height across parental-education groups
Template 3 · Two continuous variables: regression
The question: does weight predict height at baseline? Two continuous variables — an outcome (height) and a predictor (weight) — call for simple linear regression, which fits the best straight line through the cloud of points and tells you how steep and how reliable it is.
Clean
No recoding this time, since both variables are already numeric.
For regression, the first look is a scatter plot with a fitted line.
ggplot(clean, aes(x = weight, y = height)) +geom_point(alpha =0.5) +geom_smooth(method ="lm", se =TRUE, color ="steelblue") +labs(title ="Height against weight", x ="Weight", y ="Height") +theme_minimal()
Figure 7: Height against weight, with a fitted line
Call:
lm(formula = height ~ weight, data = clean_no_sibs)
Residuals:
Min 1Q Median 3Q Max
-10.2213 -2.3722 -0.0727 2.4600 9.0907
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 49.557264 0.609322 81.33 <2e-16 ***
weight 0.081739 0.006359 12.85 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 3.624 on 460 degrees of freedom
Multiple R-squared: 0.2643, Adjusted R-squared: 0.2627
F-statistic: 165.2 on 1 and 460 DF, p-value: < 2.2e-16
The weight row’s Estimate is the slope — the predicted change in height for a one-unit rise in weight — and its p-value tests whether that slope differs from zero. R-squared is the share of variation in height the model explains.
Check assumptions (after fitting)
Regression’s assumptions live in the residuals, so we check them after fitting: residuals should be normal (Shapiro + Q-Q) and have constant variance (the Breusch-Pagan test; p > 0.05 is good). The residuals-vs-fitted plot should look like a flat, shapeless band — no funnel, no curve.
shapiro.test(residuals(reg_result)) # normality of residuals
Shapiro-Wilk normality test
data: residuals(reg_result)
W = 0.99696, p-value = 0.5451
studentized Breusch-Pagan test
data: reg_result
BP = 0.47918, df = 1, p-value = 0.4888
ggplot(data.frame(fitted =fitted(reg_result), residuals =residuals(reg_result)),aes(x = fitted, y = residuals)) +geom_point(alpha =0.5) +geom_hline(yintercept =0, linetype ="dashed", color ="steelblue") +geom_smooth(se =FALSE, color ="tomato") +labs(title ="Residuals vs. fitted values", x ="Fitted", y ="Residual") +theme_minimal()
Figure 8: Residuals against fitted values
Effect size: R² and standardized beta
For simple regression, R-squaredis the effect size (0.02 small, 0.13 medium, 0.26 large). The standardized beta re-expresses the slope in standard-deviation units, so it no longer depends on the measurement scale.
ggplot(clean_no_sibs, aes(x = weight, y = height)) +geom_point(alpha =0.4) +geom_smooth(method ="lm", se =TRUE, color ="steelblue", fill ="lightblue") +labs(title ="Height predicted by weight", x ="Weight", y ="Height") +theme_minimal()
Figure 9: Simple linear regression of height on weight
A fourth template: chi-squared
What if both of your variables are categorical — say, income band and whether a child feels their neighbourhood is safe? Then none of the three tests above fit, and you want a chi-squared test of independence. It has its own template and its own walk-through:
TipGoing deeper
The full chi-squared workflow — contingency tables, expected-count checks, Cramér’s V and a grouped bar chart — is on the chi-squared deep-dive page.
Exercise · make a template your own
NoteExercise · ~15 min
Pick whichever template matches a question you care about, and swap in your own variables from the data dictionary. For example: is there a sex difference in weight (t-test)? Does household income (three levels) relate to a cognition score (ANOVA)? Does screen time predict a mental-health score (regression)?
Change only the select() block and the variable names — the rest of the template carries over.
TipSolution — weight by sex (t-test)
sol <- data |>select(participant_id, session_id,family_id = ab_g_stc__design_id__fam,sex = ab_g_stc__cohort_sex,weight = ph_y_anthr__weight_mean) |>filter(session_id =="ses-00A") |>mutate(sex =case_when(sex ==1~"Male", sex ==2~"Female", .default =NA) |>factor(levels =c("Female", "Male"))) |> tidyr::drop_na(family_id, sex, weight)set.seed(1996)sol_no_sibs <- sol |>group_by(family_id) |>slice_sample(n =1) |>ungroup()t.test(weight ~ sex, data = sol_no_sibs, var.equal =TRUE)
Two Sample t-test
data: weight by sex
t = 0.85742, df = 460, p-value = 0.3917
alternative hypothesis: true difference in means between group Female and group Male is not equal to 0
95 percent confidence interval:
-2.741556 6.985743
sample estimates:
mean in group Female mean in group Male
93.07878 90.95668
Only the two variable names changed from Template 1 — that is the whole point of a template.
What you can now do
Match a research question to the right test by looking at the shape of its variables — two groups, many groups, two numbers, or two categories.
Clean a longitudinal extract down to one baseline row per family, and say out loud what your missing-data choice costs.
Check the assumptions a test rests on — normality, equal variances, independence — instead of assuming them.
Report an effect size alongside the p-value, and read a confidence interval.
Produce the figure that goes next to the test on a poster.
From here to your proto-poster
Module 4 on Nov 12 is a hands-on project session. You will take one of these templates, run it end to end on a question of your choosing, and assemble the result into a proto-poster — a first, rough draft of the kind of poster you would bring to a conference.
Here is an example of the finished shape to aim for:
Because Module 4 builds directly on this material, Module 3 is a prerequisite. Come with a question in mind and a template that fits it.
Slides & readings
The slides from the live session, plus two short papers that go deeper on the two judgement calls this module keeps running into — how big an effect has to be to matter, and what to do about missing rows.
The following recording is of the live workshop hosted on Oct 29, 2026.
Warning
The topics covered during the live session is a smaller subset of all the materials displayed above. We highly recommend you go through this entire page and the exercises to get comfortable with the contents / topics of Module 3.
Going further
longitudinal.dev — a collection of statistical analyses for longitudinal studies, written with ABCD in mind