install.packages(c(
"tidyverse", "janitor", "readxl", "haven", "data.table", "skimr",
"survey", "srvyr", "broom", "performance", "lme4", "boot", "rsample",
"epitools", "epiR", "MatchIt", "gtsummary", "tableone", "mice",
"survival", "survminer", "forecast", "poLCA", "pwr", "gt", "here",
"sf", "tigris", "shiny", "patchwork", "scales",
"NHANES", "cluster", "sandwich", "lmtest"
))My R Reference Guide
Data transformation, visualization, statistics, and epidemiology
1 How to Use This Guide
The guide moves in the order of a real project: get data in, clean it, transform it, visualize it, run statistics, apply epidemiology designs, then share results. Every section follows the same pattern:
- What it’s for: when you would reach for it
- Packages: which package does what
- Worked example: commented code using a dataset built into R
- Watch out for: common mistakes
- Learn more: official documentation
Parts 5 and 6 (epidemiology and pattern finding) are written as walkthroughs: each starts with a research question and hypothesis, explains why each step is done, and shows how to read the results.
1.1 Install everything once
Run this one time in the console (not in this file).
library(tidyverse) # loads dplyr, tidyr, ggplot2, stringr, forcats, lubridate, purrr, readr1.2 Built-in datasets used here
| Dataset | What it contains | Used for |
|---|---|---|
mtcars |
32 cars, engine and mileage data | filtering, regression |
iris |
150 flowers, 3 species | grouping, PCA |
airquality |
New York air readings with missing values | missing data, dates |
ToothGrowth |
guinea pig tooth growth by vitamin C dose | comparing groups |
infert |
matched case-control study of infertility | odds ratios, conditional logistic regression |
lung (survival) |
lung cancer survival times | survival analysis |
AirPassengers |
monthly airline passengers 1949 to 1960 | forecasting |
api (survey) |
California school survey sample | survey weighting |
NHANESraw (NHANES) |
real NHANES 2009-2012 data with design variables | survey weighting, prevalence |
trial (gtsummary) |
200 patients randomized to two drugs | Table 1, confounding |
lalonde (MatchIt) |
job training program data | propensity score matching |
Seatbelts |
monthly UK road deaths 1969 to 1984 | interrupted time series |
USArrests |
crime and urbanization by US state | PCA, clustering |
carcinoma (poLCA) |
7 pathologists rating 118 slides | latent class analysis |
2 Part 1: Getting Data In and Cleaning It
2.1 Importing data
What it’s for: reading files into R as data frames.
| Package | Function | File type |
|---|---|---|
| readr | read_csv() |
.csv |
| readxl | read_excel() |
.xls, .xlsx |
| haven | read_xpt(), read_sas(), read_dta(), read_sav() |
SAS (NHANES), Stata, SPSS |
| here | here() |
builds file paths that work on any computer |
library(readxl); library(haven); library(here)
df <- read_csv(here("data", "my_file.csv"))
xl <- read_excel(here("data", "my_file.xlsx"), sheet = 1)
demo <- read_xpt(here("data", "DEMO_J.XPT")) # NHANES demographics fileWatch out for: read_csv() (readr, underscore) is faster and tidier than base read.csv(). NHANES files are .XPT, so use read_xpt().
2.2 First look and quick cleaning
What it’s for: understanding a dataset and fixing messy names before doing anything else.
library(janitor); library(skimr)
glimpse(airquality) # column types and first valuesRows: 153
Columns: 6
$ Ozone <int> 41, 36, 12, 18, NA, 28, 23, 19, 8, NA, 7, 16, 11, 14, 18, 14, …
$ Solar.R <int> 190, 118, 149, 313, NA, NA, 299, 99, 19, 194, NA, 256, 290, 27…
$ Wind <dbl> 7.4, 8.0, 12.6, 11.5, 14.3, 14.9, 8.6, 13.8, 20.1, 8.6, 6.9, 9…
$ Temp <int> 67, 72, 74, 62, 56, 66, 65, 59, 61, 69, 74, 69, 66, 68, 58, 64…
$ Month <int> 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,…
$ Day <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,…
skim(airquality) # summary, missing counts, mini histograms| Name | airquality |
| Number of rows | 153 |
| Number of columns | 6 |
| _______________________ | |
| Column type frequency: | |
| numeric | 6 |
| ________________________ | |
| Group variables | None |
Variable type: numeric
| skim_variable | n_missing | complete_rate | mean | sd | p0 | p25 | p50 | p75 | p100 | hist |
|---|---|---|---|---|---|---|---|---|---|---|
| Ozone | 37 | 0.76 | 42.13 | 32.99 | 1.0 | 18.00 | 31.5 | 63.25 | 168.0 | ▇▃▂▁▁ |
| Solar.R | 7 | 0.95 | 185.93 | 90.06 | 7.0 | 115.75 | 205.0 | 258.75 | 334.0 | ▅▃▅▇▅ |
| Wind | 0 | 1.00 | 9.96 | 3.52 | 1.7 | 7.40 | 9.7 | 11.50 | 20.7 | ▂▇▇▃▁ |
| Temp | 0 | 1.00 | 77.88 | 9.47 | 56.0 | 72.00 | 79.0 | 85.00 | 97.0 | ▂▃▇▇▃ |
| Month | 0 | 1.00 | 6.99 | 1.42 | 5.0 | 6.00 | 7.0 | 8.00 | 9.0 | ▇▇▇▇▇ |
| Day | 0 | 1.00 | 15.80 | 8.86 | 1.0 | 8.00 | 16.0 | 23.00 | 31.0 | ▇▇▇▇▆ |
messy <- tibble(`Patient ID` = 1:3, `Age (yrs)` = c(30, 30, 45))
messy |> clean_names() # becomes patient_id, age_yrs# A tibble: 3 × 2
patient_id age_yrs
<int> <dbl>
1 1 30
2 2 30
3 3 45
messy |> get_dupes(`Age (yrs)`) # find duplicate rows# A tibble: 2 × 3
`Age (yrs)` dupe_count `Patient ID`
<dbl> <int> <int>
1 30 2 1
2 30 2 2
mtcars |> tabyl(cyl, am) # quick cross-tab cyl 0 1
4 3 8
6 4 3
8 12 2
Watch out for: clean names right after importing so every later step uses consistent snake_case.
3 Part 2: Transforming Data
3.1 The pipe
|> means “and then.” df |> filter(x > 1) |> select(y) reads “take df, and then filter, and then select.” The older %>% from magrittr works the same way.
3.2 Selecting columns and filtering rows
| Package | Function | Does |
|---|---|---|
| dplyr | select() |
keep or drop columns |
| dplyr | filter() |
keep rows that meet a condition |
| dplyr | arrange() |
sort rows |
| dplyr | distinct(), slice_max() |
unique rows, top rows |
mtcars |>
select(mpg, cyl, hp) |> # keep three columns
filter(cyl == 4, mpg > 25) |> # comma means AND
arrange(desc(mpg)) # highest mpg first mpg cyl hp
Toyota Corolla 33.9 4 65
Fiat 128 32.4 4 66
Honda Civic 30.4 4 52
Lotus Europa 30.4 4 113
Fiat X1-9 27.3 4 66
Porsche 914-2 26.0 4 91
# Base R equivalent
mtcars[mtcars$cyl == 4 & mtcars$mpg > 25, c("mpg", "cyl", "hp")] mpg cyl hp
Fiat 128 32.4 4 66
Honda Civic 30.4 4 52
Toyota Corolla 33.9 4 65
Fiat X1-9 27.3 4 66
Porsche 914-2 26.0 4 91
Lotus Europa 30.4 4 113
# Helpers
iris |> select(starts_with("Petal")) |> head(3) Petal.Length Petal.Width
1 1.4 0.2
2 1.4 0.2
3 1.3 0.2
mtcars |> filter(cyl %in% c(4, 6)) |> nrow()[1] 18
Watch out for: use == to compare and = only to name arguments. filter() silently drops rows where the condition is NA.
3.3 Creating and changing columns
mtcars |>
mutate(
kpl = mpg * 0.425, # new numeric column
power = case_when( # categories from rules
hp < 100 ~ "low",
hp < 200 ~ "medium",
TRUE ~ "high" # everything else
),
heavy = if_else(wt > 3.5, "yes", "no") # two-way choice
) |>
select(mpg, kpl, hp, power, heavy) |>
head() mpg kpl hp power heavy
Mazda RX4 21.0 8.9250 110 medium no
Mazda RX4 Wag 21.0 8.9250 110 medium no
Datsun 710 22.8 9.6900 93 low no
Hornet 4 Drive 21.4 9.0950 110 medium no
Hornet Sportabout 18.7 7.9475 175 medium no
Valiant 18.1 7.6925 105 medium no
Watch out for: case_when() checks rules top to bottom and stops at the first match, so order matters.
3.4 Grouping and summarizing
iris |>
group_by(Species) |>
summarise(
n = n(),
mean_petal = mean(Petal.Length),
sd_petal = sd(Petal.Length)
)# A tibble: 3 × 4
Species n mean_petal sd_petal
<fct> <int> <dbl> <dbl>
1 setosa 50 1.46 0.174
2 versicolor 50 4.26 0.470
3 virginica 50 5.55 0.552
mtcars |> count(cyl, gear) # shortcut for group_by + n() cyl gear n
1 4 3 1
2 4 4 8
3 4 5 2
4 6 3 2
5 6 4 4
6 6 5 1
7 8 3 12
8 8 5 2
# data.table: very fast for millions of rows
library(data.table)
dt <- as.data.table(iris)
dt[, .(mean_petal = mean(Petal.Length)), by = Species] Species mean_petal
<fctr> <num>
1: setosa 1.462
2: versicolor 4.260
3: virginica 5.552
Watch out for: add .groups = "drop" or ungroup() afterward so later steps are not still grouped.
Learn more: dplyr, data.table
3.5 Factors and categories (forcats)
What it’s for: controlling category order and labels, which matters for tables, plots, and the reference group in regression.
df <- mtcars |> mutate(cyl = factor(cyl))
levels(df$cyl)[1] "4" "6" "8"
df |> mutate(cyl = fct_relevel(cyl, "8")) |> pull(cyl) |> levels() # 8 becomes reference[1] "8" "4" "6"
df |> mutate(cyl = fct_recode(cyl, Four = "4", Six = "6", Eight = "8")) |> count(cyl) cyl n
1 Four 11
2 Six 7
3 Eight 14
df |> mutate(cyl = fct_infreq(cyl)) |> count(cyl) # order by frequency cyl n
1 8 14
2 4 11
3 6 7
df |> mutate(cyl = fct_lump_n(cyl, n = 2)) |> count(cyl) # rare levels become "Other" cyl n
1 4 11
2 8 14
3 Other 7
Learn more: forcats
3.6 Text cleaning (stringr)
x <- c(" Type 2 Diabetes ", "type 1 diabetes", "HTN", "Hypertension")
str_trim(x) # remove extra spaces[1] "Type 2 Diabetes" "type 1 diabetes" "HTN" "Hypertension"
str_to_lower(x) # lowercase[1] " type 2 diabetes " "type 1 diabetes" "htn"
[4] "hypertension"
str_detect(x, regex("diabetes", ignore_case = TRUE)) # TRUE/FALSE[1] TRUE TRUE FALSE FALSE
str_replace(x, "HTN", "Hypertension")[1] " Type 2 Diabetes " "type 1 diabetes" "Hypertension"
[4] "Hypertension"
str_extract("ID-00452", "[0-9]+") # pull numbers out[1] "00452"
str_c("Patient", 1:3, sep = "_") # paste together[1] "Patient_1" "Patient_2" "Patient_3"
Watch out for: stringr patterns are regular expressions, so . means “any character.” Use fixed(".") for a literal dot.
Learn more: stringr
3.7 Dates and times (lubridate)
aq <- airquality |> mutate(date = make_date(1973, Month, Day))
head(aq$date)[1] "1973-05-01" "1973-05-02" "1973-05-03" "1973-05-04" "1973-05-05"
[6] "1973-05-06"
ymd("2026-11-20"); mdy("11/20/2026"); dmy("20-11-2026")[1] "2026-11-20"
[1] "2026-11-20"
[1] "2026-11-20"
# lubridate:: makes sure R uses lubridate's version (data.table has its own wday() and month())
aq |> mutate(weekday = lubridate::wday(date, label = TRUE), mon = lubridate::month(date, label = TRUE)) |>
select(date, weekday, mon) |> head(3) date weekday mon
1 1973-05-01 Tue May
2 1973-05-02 Wed May
3 1973-05-03 Thu May
# Time between dates, useful for follow-up time
interval(ymd("2020-01-15"), ymd("2023-06-01")) / years(1)[1] 3.375342
ymd("2026-01-01") + days(90) # 90-day window[1] "2026-04-01"
Learn more: lubridate
3.8 Missing values and multiple imputation
What it’s for: finding, removing, filling, or imputing NAs.
colSums(is.na(airquality)) # NA count per column Ozone Solar.R Wind Temp Month Day
37 7 0 0 0 0
airquality |> drop_na(Ozone) |> nrow() # drop rows missing Ozone[1] 116
airquality |> replace_na(list(Solar.R = 0)) |> head(5) Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 NA 0 14.3 56 5 5
mean(airquality$Ozone) # NA[1] NA
mean(airquality$Ozone, na.rm = TRUE) # ignore NA[1] 42.12931
airquality |> fill(Ozone, .direction = "down") |> head(5) # carry forward Ozone Solar.R Wind Temp Month Day
1 41 190 7.4 67 5 1
2 36 118 8.0 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 18 NA 14.3 56 5 5
Dropping rows can bias results when missingness is not random. Multiple imputation (mice) creates several filled-in datasets, fits the model on each, and pools the results.
library(mice)
imp <- mice(airquality, m = 5, seed = 123, printFlag = FALSE)
fit <- with(imp, lm(Ozone ~ Temp + Wind))
summary(pool(fit)) term estimate std.error statistic df p.value
1 (Intercept) -66.004935 22.7838035 -2.897011 41.47674 5.991132e-03
2 Temp 1.769961 0.2392335 7.398466 48.30852 1.741085e-09
3 Wind -2.961797 0.6652761 -4.451982 36.10737 7.867647e-05
Learn more: tidyr, mice, van Buuren, Flexible Imputation of Missing Data (free online)
3.9 Reshaping wide and long (tidyr)
What it’s for: “long” format (one row per measurement) is what ggplot2 and most models want. “Wide” is easier to read.
wide <- iris |> mutate(id = row_number()) |> head(3)
long <- wide |>
pivot_longer(cols = Sepal.Length:Petal.Width,
names_to = "measure", values_to = "cm")
long# A tibble: 12 × 4
Species id measure cm
<fct> <int> <chr> <dbl>
1 setosa 1 Sepal.Length 5.1
2 setosa 1 Sepal.Width 3.5
3 setosa 1 Petal.Length 1.4
4 setosa 1 Petal.Width 0.2
5 setosa 2 Sepal.Length 4.9
6 setosa 2 Sepal.Width 3
7 setosa 2 Petal.Length 1.4
8 setosa 2 Petal.Width 0.2
9 setosa 3 Sepal.Length 4.7
10 setosa 3 Sepal.Width 3.2
11 setosa 3 Petal.Length 1.3
12 setosa 3 Petal.Width 0.2
long |> pivot_wider(names_from = measure, values_from = cm)# A tibble: 3 × 6
Species id Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <int> <dbl> <dbl> <dbl> <dbl>
1 setosa 1 5.1 3.5 1.4 0.2
2 setosa 2 4.9 3 1.4 0.2
3 setosa 3 4.7 3.2 1.3 0.2
# Split and combine columns
tibble(bp = c("120/80", "135/90")) |> separate_wider_delim(bp, "/", names = c("sys", "dia"))# A tibble: 2 × 2
sys dia
<chr> <chr>
1 120 80
2 135 90
3.10 Joining tables (dplyr)
patients <- tibble(id = 1:4, age = c(34, 51, 29, 62))
labs <- tibble(id = c(1, 2, 2, 5), a1c = c(5.4, 7.1, 6.8, 6.0))
left_join(patients, labs, by = "id") # keep all patients# A tibble: 5 × 3
id age a1c
<dbl> <dbl> <dbl>
1 1 34 5.4
2 2 51 7.1
3 2 51 6.8
4 3 29 NA
5 4 62 NA
inner_join(patients, labs, by = "id") # only matches# A tibble: 3 × 3
id age a1c
<dbl> <dbl> <dbl>
1 1 34 5.4
2 2 51 7.1
3 2 51 6.8
anti_join(patients, labs, by = "id") # patients with no labs# A tibble: 2 × 2
id age
<int> <dbl>
1 3 29
2 4 62
full_join(patients, labs, by = "id") # everyone# A tibble: 6 × 3
id age a1c
<dbl> <dbl> <dbl>
1 1 34 5.4
2 2 51 7.1
3 2 51 6.8
4 3 29 NA
5 4 62 NA
6 5 NA 6
Watch out for: if a key repeats (patient 2 has two labs), rows multiply. Check nrow() before and after every join.
3.11 Repeating steps (across and purrr)
# Same function on many columns
iris |> group_by(Species) |> summarise(across(where(is.numeric), mean))# A tibble: 3 × 5
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 5.01 3.43 1.46 0.246
2 versicolor 5.94 2.77 4.26 1.33
3 virginica 6.59 2.97 5.55 2.03
mtcars |> mutate(across(c(mpg, hp), ~ round(.x / max(.x), 2))) |> head(3) mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 0.62 6 160 0.33 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 0.62 6 160 0.33 3.90 2.875 17.02 0 1 4 4
Datsun 710 0.67 4 108 0.28 3.85 2.320 18.61 1 1 4 1
# Same model for each group
mtcars |>
split(~ cyl) |>
map(\(d) lm(mpg ~ wt, data = d)) |>
map_dbl(\(m) coef(m)[["wt"]]) 4 6 8
-5.647025 -2.780106 -2.192438
# Read many files at once
# files <- list.files("data", pattern = ".csv", full.names = TRUE)
# all <- map(files, read_csv) |> list_rbind()Learn more: purrr
4 Part 3: Visualizing with ggplot2
4.1 The grammar
Every plot is built from layers joined with +:
ggplot(data, aes(x, y, color, fill, size, shape)): data and mappingsgeom_*(): the shape (points, bars, lines)labs(): wordsscale_*(): colors and axesfacet_*(): small multiplestheme(): everything visual that is not data
4.2 Common geoms
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point() # scatter
p + geom_point() + geom_smooth(method = "lm") # with trend line
ggplot(mtcars, aes(factor(cyl))) + geom_bar() # counts
ggplot(iris, aes(Species, Petal.Length)) + geom_boxplot()
ggplot(iris, aes(Petal.Length)) + geom_histogram(bins = 20)
ggplot(airquality, aes(Day, Temp, color = factor(Month))) + geom_line()
ggplot(iris, aes(Petal.Length, fill = Species)) + geom_density(alpha = 0.5)
ggplot(ToothGrowth, aes(factor(dose), len)) + geom_violin() + geom_jitter(width = 0.1)geom_bar() counts rows for you. geom_col() uses a y value you already calculated.
4.3 Titles, subtitles, captions, and labels
base <- ggplot(mtcars, aes(wt, mpg, color = factor(cyl))) + geom_point(size = 3)
base + labs(
title = "Heavier cars get fewer miles per gallon",
subtitle = "Motor Trend 1974 road tests",
caption = "Source: mtcars dataset",
tag = "A", # panel letter for figures
x = "Weight (1,000 lbs)",
y = "Miles per gallon",
color = "Cylinders" # legend title
)4.4 Text style: bold, italic, size, angle, alignment
All text is styled with element_text() inside theme().
| Argument | Options | Meaning |
|---|---|---|
face |
“plain”, “bold”, “italic”, “bold.italic” | font style |
size |
number | points |
color |
“navy”, “#1B4F72” | color |
hjust |
0, 0.5, 1 | left, center, right |
vjust |
0, 0.5, 1 | bottom, middle, top |
angle |
0 to 360 | slant the text |
family |
“serif”, “sans”, “mono” | font |
margin |
margin(t, r, b, l) |
space around text |
lineheight |
number | spacing between lines |
Theme pieces you can target: plot.title, plot.subtitle, plot.caption, axis.title.x, axis.title.y, axis.text.x, axis.text.y, legend.title, legend.text, strip.text (facet labels).
base +
labs(title = "Heavier cars get fewer miles per gallon",
subtitle = "Motor Trend 1974", caption = "Source: mtcars",
x = "Weight", y = "MPG", color = "Cylinders") +
theme(
plot.title = element_text(face = "bold", size = 16, hjust = 0.5),
plot.subtitle = element_text(face = "italic", hjust = 0.5, color = "gray40"),
plot.caption = element_text(face = "italic", hjust = 0, size = 8),
plot.title.position = "plot", # align title with whole plot
axis.title.x = element_text(face = "bold", margin = margin(t = 10)),
axis.text.x = element_text(angle = 45, hjust = 1), # slanted labels
legend.title = element_text(face = "bold")
)Italic inside a label (like species names or p):
ggplot(iris, aes(Sepal.Length, Petal.Length)) + geom_point() +
labs(title = expression(paste("Petal length in ", italic("Iris"), " species")),
y = expression(Petal~length~(cm^2)))4.5 Legend placement
base + theme(legend.position = "bottom") # "top", "left", "right", "none"base + theme(legend.position = "inside", legend.position.inside = c(0.85, 0.8))base + guides(color = guide_legend(nrow = 1, reverse = TRUE))4.6 Annotations
base +
annotate("text", x = 5, y = 30, label = "Light, efficient cars", fontface = "bold") +
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = 25, ymax = 35, alpha = 0.1, fill = "blue") +
annotate("segment", x = 4.5, xend = 5.3, y = 20, yend = 15.5,
arrow = arrow(length = unit(0.2, "cm"))) +
geom_hline(yintercept = mean(mtcars$mpg), linetype = "dashed") +
geom_text(data = mtcars |> rownames_to_column("car") |> filter(mpg > 30),
aes(wt, mpg, label = car), vjust = -1, size = 3, inherit.aes = FALSE)4.7 Colors and scales
library(scales)
base + scale_color_brewer(palette = "Set2") # ColorBrewer palettesbase + scale_color_viridis_d() # colorblind friendlybase + scale_color_manual(values = c("4" = "#1B9E77", "6" = "#D95F02", "8" = "#7570B3"))ggplot(mtcars, aes(wt, mpg, color = hp)) + geom_point() + scale_color_gradient(low = "gold", high = "red")base + scale_x_continuous(limits = c(1, 6), breaks = 1:6) +
scale_y_continuous(labels = label_number(suffix = " mpg"))ggplot(mtcars, aes(factor(cyl))) + geom_bar(aes(y = after_stat(count / sum(count)))) +
scale_y_continuous(labels = label_percent())base + coord_flip() # swap axesbase + scale_y_log10() # log scale4.8 Facets
ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~ cyl, labeller = label_both)ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_grid(am ~ cyl, scales = "free_y")4.9 Themes
base + theme_minimal()
base + theme_classic()
base + theme_bw()
base + theme_void()Set one theme for the whole document: theme_set(theme_minimal(base_size = 13)).
Other theme elements: panel.grid.minor = element_blank() removes minor grid lines, panel.background = element_rect(fill = "white"), axis.line = element_line(color = "black").
4.10 Combining plots (patchwork)
library(patchwork)
p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p2 <- ggplot(mtcars, aes(factor(cyl))) + geom_bar()
(p1 | p2) + plot_annotation(title = "Two views of mtcars", tag_levels = "A")Learn more: ggplot2 reference, Wickham, ggplot2: Elegant Graphics for Data Analysis (free online), R Graph Gallery
4.11 Maps (sf and tigris)
What it’s for: county or state maps, such as rates by county for health equity work.
library(sf); library(tigris)
options(tigris_use_cache = TRUE)
wa <- counties(state = "WA", cb = TRUE) # downloads WA county shapes
wa$fake_rate <- runif(nrow(wa), 5, 25) # replace with your data via left_join
ggplot(wa) +
geom_sf(aes(fill = fake_rate), color = "white") +
scale_fill_viridis_c(name = "Rate per 100k") +
labs(title = "Example rate by Washington county") +
theme_void()Join your data to the map with left_join(wa, my_data, by = "GEOID") using the county FIPS code.
Learn more: sf, tigris, Lovelace et al., Geocomputation with R (free online)
5 Part 4: Statistics
5.1 Descriptive statistics
summary(mtcars$mpg) Min. 1st Qu. Median Mean 3rd Qu. Max.
10.40 15.43 19.20 20.09 22.80 33.90
mtcars |> summarise(mean = mean(mpg), median = median(mpg), sd = sd(mpg),
iqr = IQR(mpg), min = min(mpg), max = max(mpg)) mean median sd iqr min max
1 20.09062 19.2 6.026948 7.375 10.4 33.9
quantile(mtcars$mpg, c(0.25, 0.5, 0.75)) 25% 50% 75%
15.425 19.200 22.800
table(mtcars$cyl); prop.table(table(mtcars$cyl))
4 6 8
11 7 14
4 6 8
0.34375 0.21875 0.43750
5.2 Which test do I use?
| Outcome | Groups | Test | R function |
|---|---|---|---|
| Numeric | 2 independent | t-test (or Wilcoxon if skewed) | t.test(), wilcox.test() |
| Numeric | 2 paired | paired t-test | t.test(paired = TRUE) |
| Numeric | 3+ | ANOVA (or Kruskal-Wallis) | aov(), kruskal.test() |
| Categorical | any | chi-square (Fisher if counts < 5) | chisq.test(), fisher.test() |
| Two numerics | none | correlation | cor.test() |
t.test(len ~ supp, data = ToothGrowth) # two groups
Welch Two Sample t-test
data: len by supp
t = 1.9153, df = 55.309, p-value = 0.06063
alternative hypothesis: true difference in means between group OJ and group VC is not equal to 0
95 percent confidence interval:
-0.1710156 7.5710156
sample estimates:
mean in group OJ mean in group VC
20.66333 16.96333
wilcox.test(len ~ supp, data = ToothGrowth)
Wilcoxon rank sum exact test
data: len by supp
W = 575.5, p-value = 0.06366
alternative hypothesis: true location shift is not equal to 0
a <- aov(len ~ factor(dose), data = ToothGrowth); summary(a) Df Sum Sq Mean Sq F value Pr(>F)
factor(dose) 2 2426 1213 67.42 9.53e-16 ***
Residuals 57 1026 18
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
TukeyHSD(a) # which pairs differ Tukey multiple comparisons of means
95% family-wise confidence level
Fit: aov(formula = len ~ factor(dose), data = ToothGrowth)
$`factor(dose)`
diff lwr upr p adj
1-0.5 9.130 5.901805 12.358195 0.00e+00
2-0.5 15.495 12.266805 18.723195 0.00e+00
2-1 6.365 3.136805 9.593195 4.25e-05
chisq.test(table(mtcars$cyl, mtcars$am))
Pearson's Chi-squared test
data: table(mtcars$cyl, mtcars$am)
X-squared = 8.7407, df = 2, p-value = 0.01265
fisher.test(table(mtcars$vs, mtcars$am))
Fisher's Exact Test for Count Data
data: table(mtcars$vs, mtcars$am)
p-value = 0.4727
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
0.3825342 10.5916087
sample estimates:
odds ratio
1.956055
cor.test(mtcars$mpg, mtcars$wt) # Pearson
Pearson's product-moment correlation
data: mtcars$mpg and mtcars$wt
t = -9.559, df = 30, p-value = 1.294e-10
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.9338264 -0.7440872
sample estimates:
cor
-0.8676594
cor.test(mtcars$mpg, mtcars$wt, method = "spearman") # rank based
Spearman's rank correlation rho
data: mtcars$mpg and mtcars$wt
S = 10292, p-value = 1.488e-11
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
-0.886422
round(cor(mtcars[, 1:5]), 2) # correlation matrix mpg cyl disp hp drat
mpg 1.00 -0.85 -0.85 -0.78 0.68
cyl -0.85 1.00 0.90 0.83 -0.70
disp -0.85 0.90 1.00 0.79 -0.71
hp -0.78 0.83 0.79 1.00 -0.45
drat 0.68 -0.70 -0.71 -0.45 1.00
5.3 Multiple testing
Running many tests inflates false positives. Adjust p-values:
pvals <- c(0.01, 0.02, 0.03, 0.04, 0.20)
p.adjust(pvals, method = "bonferroni") # strict[1] 0.05 0.10 0.15 0.20 1.00
p.adjust(pvals, method = "BH") # false discovery rate, common in genomics[1] 0.05 0.05 0.05 0.05 0.20
5.4 Regression
Linear (numeric outcome) and logistic (yes/no outcome):
library(broom)
lin <- lm(mpg ~ wt + hp + factor(cyl), data = mtcars)
summary(lin)
Call:
lm(formula = mpg ~ wt + hp + factor(cyl), data = mtcars)
Residuals:
Min 1Q Median 3Q Max
-4.2612 -1.0320 -0.3210 0.9281 5.3947
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 35.84600 2.04102 17.563 2.67e-16 ***
wt -3.18140 0.71960 -4.421 0.000144 ***
hp -0.02312 0.01195 -1.934 0.063613 .
factor(cyl)6 -3.35902 1.40167 -2.396 0.023747 *
factor(cyl)8 -3.18588 2.17048 -1.468 0.153705
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 2.44 on 27 degrees of freedom
Multiple R-squared: 0.8572, Adjusted R-squared: 0.8361
F-statistic: 40.53 on 4 and 27 DF, p-value: 4.869e-11
tidy(lin, conf.int = TRUE) # clean table of coefficients# A tibble: 5 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 35.8 2.04 17.6 2.67e-16 31.7 40.0
2 wt -3.18 0.720 -4.42 1.44e- 4 -4.66 -1.70
3 hp -0.0231 0.0120 -1.93 6.36e- 2 -0.0476 0.00140
4 factor(cyl)6 -3.36 1.40 -2.40 2.37e- 2 -6.24 -0.483
5 factor(cyl)8 -3.19 2.17 -1.47 1.54e- 1 -7.64 1.27
glance(lin) # R-squared, AIC# A tibble: 1 × 12
r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.857 0.836 2.44 40.5 4.87e-11 4 -71.2 154. 163.
# ℹ 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
logit <- glm(am ~ wt + hp, data = mtcars, family = binomial)
tidy(logit, exponentiate = TRUE, conf.int = TRUE) # odds ratios# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 1.56e+8 7.44 2.53 0.0113 4.34e+3 4.08e+17
2 wt 3.09e-4 3.07 -2.63 0.00843 3.36e-8 2.30e- 2
3 hp 1.04e+0 0.0177 2.04 0.0409 1.01e+0 1.09e+ 0
Other families: family = poisson for counts, MASS::glm.nb() for overdispersed counts.
5.5 Checking model assumptions (performance)
library(performance)
check_model(lin) # linearity, normal residuals, equal variance, outliersError in `loadNamespace()`:
! there is no package called 'see'
check_collinearity(lin) # VIF; above 5 to 10 is a concern# Check for Multicollinearity
Low Correlation
Term VIF VIF 95% CI adj. VIF Tolerance Tolerance 95% CI
wt 2.58 [1.45, 3.60] 1.61 0.39 [0.28, 0.69]
hp 3.50 [1.85, 4.89] 1.87 0.29 [0.20, 0.54]
Moderate Correlation
Term VIF VIF 95% CI adj. VIF Tolerance Tolerance 95% CI
factor(cyl) 5.11 [2.71, 7.35] 1.50 0.20 [0.14, 0.37]
r2(lin)# R2 for Linear Regression
R2: 0.857
adj. R2: 0.836
5.6 Mixed models for repeated measures (lme4)
What it’s for: when the same subject is measured more than once, or people are clustered (patients in clinics). A random intercept lets each subject have their own baseline.
library(lme4)
# sleepstudy: reaction time over 10 days of sleep deprivation, 18 subjects
mm <- lmer(Reaction ~ Days + (1 | Subject), data = sleepstudy)
summary(mm)Linear mixed model fit by REML ['lmerMod']
Formula: Reaction ~ Days + (1 | Subject)
Data: sleepstudy
REML criterion at convergence: 1786.5
Scaled residuals:
Min 1Q Median 3Q Max
-3.2257 -0.5529 0.0109 0.5188 4.2506
Random effects:
Groups Name Variance Std.Dev.
Subject (Intercept) 1378.2 37.12
Residual 960.5 30.99
Number of obs: 180, groups: Subject, 18
Fixed effects:
Estimate Std. Error t value
(Intercept) 251.4051 9.7467 25.79
Days 10.4673 0.8042 13.02
Correlation of Fixed Effects:
(Intr)
Days -0.371
mm2 <- lmer(Reaction ~ Days + (Days | Subject), data = sleepstudy) # random slope too
anova(mm, mm2)Data: sleepstudy
Models:
mm: Reaction ~ Days + (1 | Subject)
mm2: Reaction ~ Days + (Days | Subject)
npar AIC BIC logLik -2*log(L) Chisq Df Pr(>Chisq)
mm 4 1802.1 1814.8 -897.04 1794.1
mm2 6 1763.9 1783.1 -875.97 1751.9 42.139 2 7.072e-10 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Learn more: lme4 vignette
5.7 Bootstrapping
What it’s for: confidence intervals without assuming a normal distribution, by resampling your data with replacement many times.
library(boot)
med_fun <- function(data, i) median(data$mpg[i])
set.seed(42)
b <- boot(mtcars, med_fun, R = 2000)
b
ORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = mtcars, statistic = med_fun, R = 2000)
Bootstrap Statistics :
original bias std. error
t1* 19.2 0.08595 1.255853
boot.ci(b, type = c("perc", "bca"))BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 2000 bootstrap replicates
CALL :
boot.ci(boot.out = b, type = c("perc", "bca"))
Intervals :
Level Percentile BCa
95% (16.85, 21.40 ) (15.90, 21.20 )
Calculations and Intervals on Original Scale
# Tidyverse style
library(rsample)
set.seed(42)
bootstraps(mtcars, times = 2000) |>
mutate(med = map_dbl(splits, \(s) median(analysis(s)$mpg))) |>
summarise(lower = quantile(med, 0.025), upper = quantile(med, 0.975))# A tibble: 1 × 2
lower upper
<dbl> <dbl>
1 16.8 21.4
5.8 Power and sample size (pwr)
Give three of four values (effect size, n, alpha, power) and pwr solves for the fourth.
library(pwr)
pwr.t.test(d = 0.5, power = 0.8, sig.level = 0.05) # n per group for a medium effect
Two-sample t test power calculation
n = 63.76561
d = 0.5
sig.level = 0.05
power = 0.8
alternative = two.sided
NOTE: n is number in *each* group
pwr.2p.test(h = ES.h(0.30, 0.20), power = 0.8) # comparing two proportions
Difference of proportion power calculation for binomial distribution (arcsine transformation)
h = 0.2319843
n = 291.6887
sig.level = 0.05
power = 0.8
alternative = two.sided
NOTE: same sample sizes
pwr.chisq.test(w = 0.3, df = 2, power = 0.8)
Chi squared power calculation
w = 0.3
N = 107.0521
df = 2
sig.level = 0.05
power = 0.8
NOTE: N is the number of observations
Cohen’s guide for d: 0.2 small, 0.5 medium, 0.8 large.
Learn more: broom, performance, pwr, Cohen, Statistical Power Analysis for the Behavioral Sciences (1988)
6 Part 5: Epidemiology in R
6.1 The big picture
Word roots: epi (Greek, “upon”) + demos (“people”) + logos (“study”). Epidemiology is the study of what falls upon a population. Cohort comes from the Latin cohors, a unit of Roman soldiers who marched together, which is a good picture of a group followed forward through time.
Almost every epidemiology analysis answers one sentence:
Is exposure X associated with outcome Y, in population Z, after accounting for other factors?
A handy way to build that sentence is PECO:
| Letter | Means | Example |
|---|---|---|
| P | Population | Adults 40 and older seen in a clinic system |
| E | Exposure | Current smoking |
| C | Comparison | Non-smokers |
| O | Outcome | First heart attack (myocardial infarction, MI) |
The study design decides which numbers you are allowed to calculate:
| Design | How people are picked | Time direction | Main measure | Walkthrough below |
|---|---|---|---|---|
| Cohort (prospective) | by exposure, then followed | forward | risk ratio, rate ratio, hazard ratio | |
| Retrospective cohort | by exposure, from old records | forward, but in the past | same as cohort | Walkthrough 1 |
| Case-control | by outcome (cases vs controls) | backward | odds ratio | Walkthrough 3 |
| Cross-sectional | a snapshot of everyone | one moment | prevalence, prevalence ratio | Walkthrough 4 |
Every walkthrough follows the same steps: question → hypothesis → data → build the analysis dataset → describe → measure → adjust → interpret.
library(survival); library(broom); library(epiR)6.2 Measures of disease frequency and association
Before writing code, it helps to know what each number means and why it is used.
6.2.1 Frequency (how common is the outcome?)
Risk (also called cumulative incidence) is the chance of getting the outcome during a set time.
\[\text{Risk} = \frac{\text{new cases during the period}}{\text{people at risk at the start}}\]
Why use it: it answers “what is my chance?” It only works when everyone is followed for the same length of time.
Incidence rate divides by person-time instead of people.
\[\text{Rate} = \frac{\text{new cases}}{\text{total person-time at risk}}\]
Why use it: in real records people are followed for different lengths of time (some move, die, or join late). Person-time gives each person credit only for the time they were actually watched. Example: 10 people followed 2 years each = 20 person-years.
Prevalence counts existing cases at one moment.
\[\text{Prevalence} = \frac{\text{people who have the condition now}}{\text{everyone in the population now}}\]
Why use it: it describes burden (how many people are living with something), which matters for planning services.
Odds compare “yes” to “no” in the same group: if 20 have the outcome and 80 do not, the odds are 20/80 = 0.25.
6.2.2 Association (does exposure change the outcome?)
Everything is built from the 2x2 table:
| Outcome yes | Outcome no | |
|---|---|---|
| Exposed | a | b |
| Unexposed | c | d |
| Measure | Formula | Used in | Why |
|---|---|---|---|
| Risk ratio (RR) | \(\frac{a/(a+b)}{c/(c+d)}\) | cohort | compares chances directly |
| Rate ratio (IRR) | \(\frac{\text{rate exposed}}{\text{rate unexposed}}\) | cohort with uneven follow-up | accounts for person-time |
| Odds ratio (OR) | \(\frac{a \times d}{b \times c}\) | case-control, logistic regression | the only valid ratio when you picked people by outcome |
| Prevalence ratio (PR) | \(\frac{\text{prevalence exposed}}{\text{prevalence unexposed}}\) | cross-sectional | easier to explain than an OR when the outcome is common |
| Hazard ratio (HR) | from a Cox model | survival analysis | compares the instant-by-instant rate of events |
Why case-control studies cannot give a risk: the researcher chooses how many cases and controls to include (for example 100 cases and 200 controls), so the share of people with the outcome is set by the researcher. The odds ratio still works because the odds of exposure among cases vs controls equals the odds of disease among exposed vs unexposed.
How to read any ratio:
- 1 means no difference between groups
- Above 1 means the outcome is more common in the exposed (RR = 2: twice the risk)
- Below 1 means less common (RR = 0.6: 40% lower risk)
- 95% confidence interval (CI): the range of values compatible with your data. If it includes 1, the data are consistent with no association.
6.2.3 Building a 2x2 table from data
Getting the row and column order right matters, because epiR expects exposed first and outcome-yes first.
# A small made-up dataset: one row per person
people <- tibble(
smoker = c(rep("Yes", 100), rep("No", 100)),
mi = c(rep("Yes", 30), rep("No", 70), rep("Yes", 12), rep("No", 88))
)
tab <- table(
Exposure = factor(people$smoker, levels = c("Yes", "No")), # exposed row first
Outcome = factor(people$mi, levels = c("Yes", "No")) # outcome-yes column first
)
tab Outcome
Exposure Yes No
Yes 30 70
No 12 88
epi.2by2(tab, method = "cohort.count") # gives risk ratio, odds ratio, attributable risk Outcome+ Outcome- Total Inc risk *
Exposure+ 30 70 100 30.00 (21.24 to 39.98)
Exposure- 12 88 100 12.00 (6.36 to 20.02)
Total 42 158 200 21.00 (15.57 to 27.31)
Point estimates and 95% CIs:
-------------------------------------------------------------------
Inc risk ratio 2.50 (1.36, 4.60)
Inc odds ratio 3.14 (1.50, 6.58)
Attrib risk in the exposed * 18.00 (6.99, 29.01)
Attrib fraction in the exposed (%) 60.00 (27.77, 78.24)
Attrib risk in the population * 9.00 (0.49, 17.51)
Attrib fraction in the population (%) 42.86 (26.67, 59.18)
E-value 4.44 (2.06, NA)
-------------------------------------------------------------------
Uncorrected chi2 test that OR = 1: chi2(1) = 9.765 Pr>chi2 = 0.002
Fisher exact test that OR = 1: Pr>chi2 = 0.003
Wald confidence limits
CI: confidence interval
* Outcomes per 100 population units
Reading the output: risk in smokers is 30/100 = 0.30 and in non-smokers 12/100 = 0.12, so RR = 0.30 / 0.12 = 2.5. Smokers in this made-up group had 2.5 times the risk. The “attributable fraction in the exposed” tells you what share of the smokers’ cases would not have happened if the exposure caused the difference.
6.3 Walkthrough 1: Building a retrospective cohort from health records
6.3.1 The question
Among adults aged 40 and older seen in a clinic system, do current smokers have a higher rate of first heart attack (MI) than non-smokers?
- Hypothesis (H1): smokers have a higher MI rate (rate ratio > 1).
- Null hypothesis (H0): the rates are equal (rate ratio = 1).
- Design: retrospective cohort. The records already exist; we look back at them, but we still move forward in time from exposure to outcome.
6.3.2 Why the steps matter
Electronic health record (EHR) and All of Us data do not come as a ready-made study. They come as separate tables of patients, visits and diagnoses. Building the cohort means turning those tables into one row per person with:
| Column | Meaning | Why we need it |
|---|---|---|
index_date |
the day each person’s follow-up starts (“time zero”) | without a clear start, you cannot measure time or decide what came first |
smoker |
exposure, measured at or before index | exposure must come before the outcome |
event |
1 if they had an MI after index, 0 if not | the outcome |
follow_years |
time from index until MI, death, or end of study | the denominator for rates |
6.3.3 The data
We will make fake but realistic EHR-style tables. In real life these would come from a database query.
set.seed(2026)
n <- 2000
true_smoking <- rbinom(n, 1, 0.25) # hidden truth used to build fake records
# Table 1: patients (one row per person)
patients <- tibble(
id = 1:n,
sex = sample(c("Female", "Male"), n, replace = TRUE),
birth_date = ymd("1940-01-01") + days(sample(0:(365 * 45), n, replace = TRUE)),
death_date = if_else(runif(n) < 0.06,
ymd("2019-01-01") + days(sample(0:1800, n, replace = TRUE)),
as.Date(NA))
)
# Table 2: visits (many rows per person), smoking recorded at each visit
visits <- tibble(id = sample(1:n, 6000, replace = TRUE)) |>
mutate(visit_date = ymd("2018-01-01") + days(sample(0:2190, n(), replace = TRUE)),
smoker = true_smoking[id])
# Table 3: diagnoses with ICD-10 codes (I21 = acute MI, I10 = hypertension)
mi <- tibble(id = 1:n, smoker = true_smoking) |>
filter(rbinom(n(), 1, 0.06 + 0.10 * smoker) == 1) |> # smokers get more MIs
mutate(dx_date = ymd("2017-01-01") + days(sample(0:2555, n(), replace = TRUE)),
dx_code = "I21")
htn <- tibble(id = sample(1:n, 800), dx_code = "I10") |>
mutate(dx_date = ymd("2017-01-01") + days(sample(0:2555, n(), replace = TRUE)))
diagnoses <- bind_rows(mi, htn) |> select(id, dx_date, dx_code) |> arrange(id, dx_date)
head(patients); head(visits); head(diagnoses)# A tibble: 6 × 4
id sex birth_date death_date
<int> <chr> <date> <date>
1 1 Female 1954-02-22 NA
2 2 Male 1951-09-17 NA
3 3 Female 1945-10-01 NA
4 4 Male 1976-09-16 NA
5 5 Female 1980-09-26 NA
6 6 Female 1964-04-12 NA
# A tibble: 6 × 3
id visit_date smoker
<int> <date> <int>
1 30 2022-05-17 0
2 1178 2021-07-27 0
3 521 2023-07-18 0
4 1717 2018-12-13 0
5 269 2020-05-03 0
6 900 2018-07-19 0
# A tibble: 6 × 3
id dx_date dx_code
<int> <date> <chr>
1 1 2023-11-11 I10
2 3 2019-02-10 I10
3 4 2023-03-07 I10
4 5 2023-01-21 I10
5 6 2022-01-09 I10
6 8 2020-07-25 I21
6.3.4 Step 1: Define the index date (time zero)
Rule: the index date is each person’s first visit during the enrollment window (2019 to 2022). Their smoking status at that visit is their exposure.
Why: picking one clear start date for everyone prevents immortal time bias, which happens when people get credit for time before they were actually in the study.
index <- visits |>
filter(visit_date >= ymd("2019-01-01"), visit_date <= ymd("2022-12-31")) |>
group_by(id) |>
slice_min(visit_date, n = 1, with_ties = FALSE) |> # first visit only
ungroup() |>
rename(index_date = visit_date)
nrow(index)[1] 1710
6.3.5 Step 2: Apply inclusion criteria
Rules: age 40 or older at index, and alive at index.
eligible <- index |>
left_join(patients, by = "id") |>
mutate(age = as.numeric(index_date - birth_date) / 365.25) |>
filter(age >= 40,
is.na(death_date) | death_date > index_date)
nrow(eligible)[1] 1516
6.3.6 Step 3: Apply exclusion criteria (lookback)
Rule: exclude anyone with an MI before their index date.
Why: we are studying new (incident) MIs. Someone who already had an MI is a prevalent case. Keeping them would mix “getting the disease” with “already having it.” In real data you also usually require a lookback window (for example 365 days of records before index), so you can actually see whether they had a prior diagnosis.
prior_mi <- eligible |>
inner_join(diagnoses |> filter(dx_code == "I21"), by = "id") |>
filter(dx_date < index_date) |>
distinct(id)
cohort <- eligible |> anti_join(prior_mi, by = "id") # anti_join drops matches
nrow(cohort)[1] 1453
6.3.7 Step 4: Define the outcome and follow-up time
Each person is followed from index until whichever comes first:
- their first MI after index (the event)
- death (censored: we stop watching, but they did not have the event)
- the end of the study, December 31, 2023 (censored)
Censoring means we do not know what happened after we stopped watching. Counting only the time we did watch keeps the rate honest.
study_end <- ymd("2023-12-31")
first_mi_after <- diagnoses |>
filter(dx_code == "I21") |>
inner_join(cohort |> select(id, index_date), by = "id") |>
filter(dx_date > index_date) |>
group_by(id) |>
summarise(mi_date = min(dx_date), .groups = "drop")
cohort <- cohort |>
left_join(first_mi_after, by = "id") |>
mutate(
end_date = pmin(mi_date, death_date, study_end, na.rm = TRUE), # earliest of the three
event = if_else(!is.na(mi_date) & mi_date == end_date, 1, 0),
follow_years = as.numeric(end_date - index_date) / 365.25
)
cohort |> select(id, index_date, smoker, mi_date, death_date, end_date, event, follow_years) |> head()# A tibble: 6 × 8
id index_date smoker mi_date death_date end_date event follow_years
<int> <date> <int> <date> <date> <date> <dbl> <dbl>
1 2 2020-12-19 0 NA NA 2023-12-31 0 3.03
2 3 2019-08-01 0 NA NA 2023-12-31 0 4.42
3 4 2021-04-17 0 NA NA 2023-12-31 0 2.70
4 6 2019-03-21 0 NA NA 2023-12-31 0 4.78
5 7 2019-01-03 0 NA NA 2023-12-31 0 4.99
6 8 2019-02-24 1 2020-07-25 NA 2020-07-25 1 1.42
6.3.8 Step 5: Check your work
Always check before analyzing. Mistakes in cohort building are silent.
stopifnot(all(cohort$follow_years > 0)) # nobody should have zero or negative time
stopifnot(n_distinct(cohort$id) == nrow(cohort)) # one row per person
# A flow table: how many people were lost at each step (this becomes your flowchart)
tibble(
step = c("Patients in database", "Visit in 2019-2022 (has an index date)",
"Age 40+ and alive at index", "No MI before index (final cohort)"),
n = c(nrow(patients), nrow(index), nrow(eligible), nrow(cohort))
)# A tibble: 4 × 2
step n
<chr> <int>
1 Patients in database 2000
2 Visit in 2019-2022 (has an index date) 1710
3 Age 40+ and alive at index 1516
4 No MI before index (final cohort) 1453
The flow table becomes the participant flowchart in a paper or poster. Reviewers always ask how many people were excluded and why.
6.3.9 Step 6: Describe and measure
rates <- cohort |>
group_by(smoker) |>
summarise(people = n(), events = sum(event), person_years = sum(follow_years),
rate_per_1000py = 1000 * events / person_years)
rates# A tibble: 2 × 5
smoker people events person_years rate_per_1000py
<int> <int> <dbl> <dbl> <dbl>
1 0 1119 27 3871. 6.98
2 1 334 30 1149. 26.1
# Crude rate ratio by hand: rate in smokers divided by rate in non-smokers
rates$rate_per_1000py[rates$smoker == 1] / rates$rate_per_1000py[rates$smoker == 0][1] 3.741683
6.3.10 Step 7: Model it, then adjust
A Poisson model with an offset gives the rate ratio with a confidence interval. The offset(log(follow_years)) tells the model each person’s amount of follow-up time, which turns counts into rates.
crude_rr <- glm(event ~ smoker + offset(log(follow_years)), family = poisson, data = cohort)
adj_rr <- glm(event ~ smoker + age + sex + offset(log(follow_years)), family = poisson, data = cohort)
tidy(crude_rr, exponentiate = TRUE, conf.int = TRUE) |> filter(term == "smoker")# A tibble: 1 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 smoker 3.74 0.265 4.97 0.000000655 2.22 6.33
tidy(adj_rr, exponentiate = TRUE, conf.int = TRUE) |> filter(term == "smoker")# A tibble: 1 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 smoker 3.74 0.265 4.97 0.000000656 2.22 6.33
A Cox model uses the exact timing of each event and gives a hazard ratio:
cox_mi <- coxph(Surv(follow_years, event) ~ smoker + age + sex, data = cohort)
tidy(cox_mi, exponentiate = TRUE, conf.int = TRUE)# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 smoker 3.73 0.265 4.96 0.000000718 2.22 6.27
2 age 1.01 0.0116 0.563 0.574 0.984 1.03
3 sexMale 0.875 0.265 -0.505 0.614 0.520 1.47
6.3.11 Step 8: Interpret
Because we built the fake data so smokers have more MIs, both ratios land well above 1. When this guide was tested, smokers had about 26 MIs per 1,000 person-years vs about 7 for non-smokers, a rate ratio of about 3.7 (95% CI about 2.2 to 6.3), and adjusting for age and sex barely changed it. A sentence for a results section would read:
“Over a median follow-up of X years, current smokers had a higher rate of incident MI than non-smokers (adjusted rate ratio Y, 95% CI Y1 to Y2), after adjusting for age and sex.”
Watch out for:
- Immortal time bias: exposure must be known at index, never defined using information from after index.
- Duplicate rows after joins: check
nrow()after every join. - Date math: subtracting dates gives days; divide by 365.25 for years.
- In All of Us, the same steps apply, but the tables are OMOP tables (
person,visit_occurrence,condition_occurrence) and codes are concept IDs rather than plain ICD codes.
6.4 Walkthrough 2: Survival analysis (time to event)
6.4.1 The question
Among patients with advanced lung cancer, do women survive longer than men, after accounting for age and physical function?
- H1: women have a lower hazard of death (HR < 1).
- H0: no difference (HR = 1).
Why survival analysis: comparing “percent who died” ignores when they died, and treats someone followed for 1 month the same as someone followed for 2 years. Survival methods use both whether and when the event happened, and they handle censoring.
6.4.2 The data
lung (from the survival package): 228 patients with advanced lung cancer from the North Central Cancer Treatment Group.
| Variable | Meaning |
|---|---|
time |
days of follow-up |
status |
1 = censored (alive at last contact), 2 = died |
sex |
1 = male, 2 = female |
age |
years |
ph.ecog |
ECOG performance score, 0 (fully active) to 4 (bedbound) |
6.4.3 Step 1: Recode
The Surv() function wants the event coded as 1 = event happened, 0 = censored.
lung2 <- lung |>
mutate(status = status - 1, # now 1 = died, 0 = censored
sex = factor(sex, levels = 1:2, labels = c("Male", "Female")))
lung2 |> count(sex, status) sex status n
1 Male 0 26
2 Male 1 112
3 Female 0 37
4 Female 1 53
6.4.4 Step 2: Kaplan-Meier curves (describe survival)
A Kaplan-Meier (KM) curve shows the share of people still alive over time. Each drop is a death; each tick mark is a censored person.
library(survminer)
km <- survfit(Surv(time, status) ~ sex, data = lung2)
km # median survival for each groupCall: survfit(formula = Surv(time, status) ~ sex, data = lung2)
n events median 0.95LCL 0.95UCL
sex=Male 138 112 270 212 310
sex=Female 90 53 426 348 550
summary(km, times = c(180, 365)) # survival at 6 months and 1 yearCall: survfit(formula = Surv(time, status) ~ sex, data = lung2)
sex=Male
time n.risk n.event survival std.err lower 95% CI upper 95% CI
180 89 49 0.644 0.0408 0.569 0.730
365 35 36 0.336 0.0434 0.261 0.433
sex=Female
time n.risk n.event survival std.err lower 95% CI upper 95% CI
180 71 14 0.842 0.0387 0.770 0.922
365 30 22 0.526 0.0597 0.421 0.658
ggsurvplot(km, conf.int = TRUE, risk.table = TRUE, pval = TRUE,
xlab = "Days since enrollment", legend.title = "",
title = "Survival by sex, advanced lung cancer")Reading it: the median survival is the day where the curve crosses 50%. The “number at risk” table below the plot shows how many people are still being followed, and estimates get shakier as it shrinks.
6.4.5 Step 3: Log-rank test (are the curves different?)
survdiff(Surv(time, status) ~ sex, data = lung2)Call:
survdiff(formula = Surv(time, status) ~ sex, data = lung2)
N Observed Expected (O-E)^2/E (O-E)^2/V
sex=Male 138 112 91.6 4.55 10.3
sex=Female 90 53 73.4 5.68 10.3
Chisq= 10.3 on 1 degrees of freedom, p= 0.001
A small p-value means the curves differ more than chance would explain. The log-rank test cannot adjust for other factors, which is why we move to Cox regression.
6.4.6 Step 4: Cox regression (adjust)
cox <- coxph(Surv(time, status) ~ sex + age + ph.ecog, data = lung2)
tidy(cox, exponentiate = TRUE, conf.int = TRUE)# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 sexFemale 0.575 0.168 -3.29 0.000986 0.414 0.799
2 age 1.01 0.00927 1.19 0.232 0.993 1.03
3 ph.ecog 1.59 0.114 4.08 0.0000445 1.27 1.99
Reading it: an HR for sexFemale around 0.58 means that at any moment, women had about 42% lower hazard of death than men of the same age and ECOG score. Each 1-point increase in ECOG raises the hazard substantially, which makes sense because worse physical function predicts worse survival.
6.4.7 Step 5: Check the proportional hazards assumption
Cox models assume the HR stays roughly constant over time. cox.zph() tests this; p-values above 0.05 suggest the assumption is reasonable.
cox.zph(cox) chisq df p
sex 2.305 1 0.13
age 0.188 1 0.66
ph.ecog 2.054 1 0.15
GLOBAL 4.464 3 0.22
Learn more: Zabor, Survival Analysis in R tutorial; Clark et al., “Survival Analysis Part I,” British Journal of Cancer (2003).
6.5 Walkthrough 3: Case-control study
6.5.1 The question
Is a history of spontaneous abortion (miscarriage) associated with secondary infertility?
- H1: women with secondary infertility (cases) are more likely to have had a prior spontaneous abortion than women without it (controls). OR > 1.
- H0: OR = 1.
Why case-control: infertility is relatively uncommon and develops over years. Following thousands of women forward would be slow and expensive. Instead we start with women who already have the outcome (cases) and compare their past exposures with women who do not (controls).
6.5.2 The data
infert (built into R): from a study in Greece (Trichopoulos et al., 1976). Each case was matched to about two controls with the same age, parity (number of prior births) and education.
| Variable | Meaning |
|---|---|
case |
1 = case (infertile), 0 = control |
spontaneous |
number of prior spontaneous abortions (0, 1, 2+) |
induced |
number of prior induced abortions (0, 1, 2+) |
stratum |
matched set ID: each case and her controls share a number |
6.5.3 Step 1: Explore
infert |> count(case) case n
1 0 165
2 1 83
infert |> count(stratum) |> count(n, name = "matched_sets") # how big are the sets? n matched_sets
1 2 1
2 3 82
6.5.4 Step 2: Define exposure and build the 2x2 table
infert2 <- infert |> mutate(spont_any = if_else(spontaneous > 0, "Yes", "No"))
tab_cc <- table(
Exposure = factor(infert2$spont_any, levels = c("Yes", "No")),
Case = factor(infert2$case, levels = c(1, 0), labels = c("Case", "Control"))
)
tab_cc Case
Exposure Case Control
Yes 55 52
No 28 113
epi.2by2(tab_cc, method = "case.control") Outcome+ Outcome- Total Odds
Exposed + 55 52 107 1.06 (0.73 to 1.55)
Exposed - 28 113 141 0.25 (0.16 to 0.37)
Total 83 165 248 0.50 (0.39 to 0.65)
Point estimates and 95% CIs:
-------------------------------------------------------------------
Exposure odds ratio 4.27 (2.44, 7.48)
Attrib fraction (est) in the exposed (%) 76.57 (59.02, 86.61)
Attrib fraction (est) in the population (%) 50.74 (43.53, 59.60)
E-value 3.55 (2.50, NA)
-------------------------------------------------------------------
Uncorrected chi2 test that OR = 1: chi2(1) = 27.184 Pr>chi2 = <0.001
Fisher exact test that OR = 1: Pr>chi2 = <0.001
Wald confidence limits
CI: confidence interval
Only the odds ratio is meaningful here, because the researchers chose the number of cases and controls.
6.5.5 Step 3: Logistic regression (adjust for other factors)
glm(case ~ spont_any + induced, data = infert2, family = binomial) |>
tidy(exponentiate = TRUE, conf.int = TRUE)# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.187 0.276 -6.08 0.00000000122 0.106 0.314
2 spont_anyYes 4.98 0.306 5.24 0.000000160 2.77 9.24
3 induced 1.42 0.205 1.73 0.0839 0.955 2.14
6.5.6 Step 4: Conditional logistic regression (respect the matching)
Why: matching makes cases and controls similar on age, parity and education. The analysis should compare each case only with her own matched controls. strata(stratum) does exactly that. Ignoring matching usually pulls the OR toward 1.
cc_model <- clogit(case ~ spont_any + induced + strata(stratum), data = infert2)
tidy(cc_model, exponentiate = TRUE, conf.int = TRUE)# A tibble: 2 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 spont_anyYes 9.64 0.416 5.44 0.0000000525 4.26 21.8
2 induced 2.45 0.289 3.10 0.00195 1.39 4.32
6.5.7 Step 5: Interpret
When tested, the crude OR from the 2x2 table was about 4.3, the ordinary logistic model gave about 5.0, and the conditional model gave about 9.6 (95% CI about 4.3 to 21.8). Respecting the matching moved the estimate further from 1, which shows why the matched analysis matters. Compared with their matched controls, infertile women had much higher odds of a prior spontaneous abortion. Because this is case-control, the sentence is about odds of past exposure, and it does not prove the abortion caused infertility.
Watch out for: recall bias (cases may remember past events differently), and choosing controls from a different population than cases.
6.6 Walkthrough 4: Cross-sectional studies and survey weighting
6.6.1 Why surveys need weights
National surveys like NHANES and BRFSS do not pick people completely at random. They use a complex sample design:
| Piece | What it is | Why it matters | NHANES variable |
|---|---|---|---|
| Weight | how many people in the US each respondent represents | some groups are oversampled on purpose (older adults, Black, Hispanic and Asian Americans, low-income people) so there are enough of them to study | WTINT2YR (interview), WTMEC2YR (exam) |
| Strata | groups the country is split into before sampling | reduces the standard error | SDMVSTRA |
| Clusters (PSUs) | areas (counties) sampled as a group | people in the same area are alike, which increases the standard error | SDMVPSU |
Analogy: imagine a class of 90 nursing students and 10 medical students. You survey 10 of each. If you average all 20 answers equally, medical students count for half your result even though they are only 10% of the class. Weighting gives each nursing student a weight of 9 (each stands for 9 people) and each medical student a weight of 1.
Without weights, your estimates are biased. Without strata and clusters, your confidence intervals are too narrow (too confident).
6.6.2 Walkthrough 4A: Seeing weighting work, where we know the truth
What is the average Academic Performance Index (API) score across all California schools?
The api data (survey package) is special: it includes the whole population of 6,194 schools (apipop) and a stratified sample of 200 (apistrat). So we can check whether weighting gets us closer to the truth.
library(survey); library(srvyr)
data(api)
# Step 1: The sample took 100 elementary (E), 50 middle (M), 50 high (H) schools...
apistrat |> count(stype) stype n
1 E 100
2 H 50
3 M 50
# ...but in the real population, elementary schools are 71% of schools
apipop |> count(stype) |> mutate(pct = n / sum(n)) stype n pct
1 E 4421 0.7137552
2 H 755 0.1218922
3 M 1018 0.1643526
High and middle schools are oversampled. Each school’s weight pw fixes this:
apistrat |> distinct(stype, pw) # each sampled elementary school stands for about 44 schools stype pw
1 E 44.21
11 M 20.36
13 H 15.10
# Step 2: Three answers to the same question
mean(apipop$api00) # the TRUTH (we normally never have this)[1] 664.7126
mean(apistrat$api00) # unweighted sample mean (biased)[1] 652.82
des <- apistrat |> as_survey_design(strata = stype, weights = pw, fpc = fpc)
des |> summarise(weighted_mean = survey_mean(api00, vartype = "ci")) # weighted# A tibble: 1 × 3
weighted_mean weighted_mean_low weighted_mean_upp
<dbl> <dbl> <dbl>
1 662. 644. 681.
When tested: the true population mean is about 665, the unweighted sample mean is about 653, and the weighted mean is about 662. The weighted answer lands much closer to the truth, which is the whole point of weights. The unweighted mean is too low because high schools, which score lower, were oversampled.
# Step 3: Subgroups and percentages
des |> group_by(stype) |> summarise(mean_api = survey_mean(api00))# A tibble: 3 × 3
stype mean_api mean_api_se
<fct> <dbl> <dbl>
1 E 674. 12.4
2 H 626. 14.9
3 M 637. 16.2
des |> summarise(pct_met_target = survey_mean(sch.wide == "Yes"))# A tibble: 1 × 2
pct_met_target pct_met_target_se
<dbl> <dbl>
1 0.828 0.0243
# Step 4: Regression that respects the design
# Question: do schools with more English learners (ell) and more students on free meals score lower?
svyglm(api00 ~ ell + meals, design = des) |> tidy(conf.int = TRUE)# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 824. 8.76 94.1 2.03e-164 807. 841.
2 ell -0.506 0.388 -1.30 1.94e- 1 -1.27 0.259
3 meals -3.11 0.276 -11.3 4.85e- 23 -3.65 -2.57
6.6.3 Walkthrough 4B: A real health question with NHANES
What was the prevalence of diagnosed diabetes among US adults in 2009 to 2012, and is it lower among physically active adults after accounting for age and sex?
- Design: cross-sectional (one snapshot per person).
- Measure: prevalence, then prevalence ratio (PR).
- H1: PR for physically active adults < 1.
The NHANES R package has real NHANES 2009-2010 and 2011-2012 data, including the design variables, in NHANESraw.
library(NHANES)Error in `library()`:
! there is no package called 'NHANES'
# Step 1: Prepare variables BEFORE building the design
nh <- NHANESraw |>
mutate(
WTMEC4YR = WTMEC2YR / 2, # 2 cycles combined, so divide weights by 2
diabetes = as.numeric(Diabetes == "Yes"),
adult = Age >= 20
)Error:
! object 'NHANESraw' not found
# Step 2: Build the design on the FULL dataset
nh_des <- nh |>
as_survey_design(ids = SDMVPSU, strata = SDMVSTRA, weights = WTMEC4YR, nest = TRUE)Error:
! object 'nh' not found
# Step 3: THEN restrict to adults with the needed data (subpopulation analysis)
adults <- nh_des |> filter(adult, !is.na(diabetes), !is.na(PhysActive))Error:
! object 'nh_des' not found
Why build the design first, then filter? The standard errors depend on the full set of clusters and strata. If you drop rows before building the design, R loses track of the sample structure and the confidence intervals come out wrong.
# Step 4: Unweighted vs weighted prevalence
nh |> filter(adult, !is.na(diabetes)) |> summarise(unweighted = mean(diabetes))Error:
! object 'nh' not found
adults |> summarise(weighted = survey_mean(diabetes, vartype = "ci"))Error:
! object 'adults' not found
# Step 5: Prevalence by physical activity
adults |> group_by(PhysActive) |> summarise(prev = survey_mean(diabetes, vartype = "ci"))Error:
! object 'adults' not found
# Step 6: Prevalence ratio, adjusted for age and sex
pr_model <- svyglm(diabetes ~ PhysActive + Age + Gender, design = adults, family = quasipoisson())Error:
! object 'adults' not found
tidy(pr_model, exponentiate = TRUE, conf.int = TRUE)Error:
! object 'pr_model' not found
Why quasipoisson instead of logistic? Logistic regression gives odds ratios. When an outcome is common (more than about 10%), the OR exaggerates the association compared with the PR. A Poisson-type model gives the PR directly, and quasipoisson avoids warnings caused by non-whole-number weights.
Interpret (tested results):
- Unweighted prevalence was about 14%, but the weighted prevalence was about 11%. The sample over-represents older adults and groups with higher diabetes rates, so skipping weights would overstate the national burden.
- Prevalence was about 14% among inactive adults vs about 8% among active adults.
- The adjusted PR for
PhysActiveYeswas about 0.69 (95% CI about 0.58 to 0.81): physically active adults had about 31% lower prevalence of diagnosed diabetes than inactive adults of the same age and sex.
Because this is a snapshot, we cannot tell which came first: activity might prevent diabetes, or having diabetes might change how active people are. That limitation is called reverse causation, and it applies to every cross-sectional study.
6.6.4 Template: raw NHANES files (CKD awareness example)
The same steps apply to files downloaded from the CDC website. This template sketches a CKD awareness question: among US adults with laboratory evidence of chronic kidney disease, what percent report ever being told they have weak or failing kidneys? Check every variable name against the codebook for your cycle.
library(haven)
# 2017-2018 cycle (suffix _J). Download from the CDC NHANES website.
demo <- read_xpt("DEMO_J.XPT") # SEQN, RIAGENDR, RIDAGEYR, design variables, weights
kiq <- read_xpt("KIQ_U_J.XPT") # KIQ022: ever told you had weak/failing kidneys (1 = yes, 2 = no)
bio <- read_xpt("BIOPRO_J.XPT") # LBXSCR: serum creatinine (mg/dL)
alb <- read_xpt("ALB_CR_J.XPT") # URDACT: urine albumin-to-creatinine ratio (mg/g)
ckd <- demo |>
left_join(kiq, by = "SEQN") |> left_join(bio, by = "SEQN") |> left_join(alb, by = "SEQN") |>
mutate(
female = RIAGENDR == 2,
kappa = if_else(female, 0.7, 0.9),
alpha = if_else(female, -0.241, -0.302),
# CKD-EPI 2021 equation (race-free)
egfr = 142 * pmin(LBXSCR / kappa, 1)^alpha * pmax(LBXSCR / kappa, 1)^-1.200 *
0.9938^RIDAGEYR * if_else(female, 1.012, 1),
has_ckd = egfr < 60 | URDACT >= 30,
aware = case_when(KIQ022 == 1 ~ 1, KIQ022 == 2 ~ 0) # 7 and 9 (refused, don't know) become NA
)
ckd_des <- ckd |>
as_survey_design(ids = SDMVPSU, strata = SDMVSTRA, weights = WTMEC2YR, nest = TRUE) # lab data = exam weight
ckd_des |>
filter(RIDAGEYR >= 20, has_ckd, !is.na(aware)) |>
summarise(pct_aware = survey_mean(aware, vartype = "ci"))Watch out for:
- Use the weight for the smallest subsample your variables come from (interview < exam < fasting subsample).
- When combining cycles, divide the weight by the number of cycles.
- If R complains about a stratum with one PSU, run
options(survey.lonely.psu = "adjust").
Learn more: CDC NHANES tutorials, srvyr, Lumley, Complex Surveys (2010), Inker et al., “New Creatinine- and Cystatin C-Based Equations to Estimate GFR without Race,” NEJM (2021).
6.7 Walkthrough 5: Confounding, Table 1 and adjustment
6.7.1 What a confounder is
A confounder is a third variable that:
- is linked to the exposure,
- affects the outcome, and
- is not a step on the path from exposure to outcome.
Example: coffee drinkers seem to get more lung cancer. Smoking is the confounder: coffee drinkers smoke more, and smoking causes lung cancer. Once you compare smokers with smokers and non-smokers with non-smokers, the coffee link disappears.
Confound comes from the Latin confundere, “to pour together” or mix up, because a confounder mixes its own effect into the exposure’s effect.
6.7.2 The question
Is Drug B associated with a different tumor response than Drug A, and does adjusting for age, grade and stage change that estimate?
trial (gtsummary package): 200 patients randomized to Drug A or Drug B.
6.7.3 Step 1: Table 1 (are the groups comparable?)
Table 1 describes baseline characteristics by exposure group. Big differences between columns point to possible confounders.
library(gtsummary)
trial |>
select(trt, age, grade, stage, response) |>
tbl_summary(by = trt, missing = "ifany",
label = list(age ~ "Age (years)", grade ~ "Tumor grade",
stage ~ "T stage", response ~ "Tumor response")) |>
add_overall() |> add_p() |> bold_labels()| Characteristic | Overall N = 2001 |
Drug A N = 981 |
Drug B N = 1021 |
p-value2 |
|---|---|---|---|---|
| Age (years) | 47 (38, 57) | 46 (37, 60) | 48 (39, 56) | 0.7 |
| Unknown | 11 | 7 | 4 | |
| Tumor grade | 0.9 | |||
| I | 68 (34%) | 35 (36%) | 33 (32%) | |
| II | 68 (34%) | 32 (33%) | 36 (35%) | |
| III | 64 (32%) | 31 (32%) | 33 (32%) | |
| T stage | 0.9 | |||
| T1 | 53 (27%) | 28 (29%) | 25 (25%) | |
| T2 | 54 (27%) | 25 (26%) | 29 (28%) | |
| T3 | 43 (22%) | 22 (22%) | 21 (21%) | |
| T4 | 50 (25%) | 23 (23%) | 27 (26%) | |
| Tumor response | 61 (32%) | 28 (29%) | 33 (34%) | 0.5 |
| Unknown | 7 | 3 | 4 | |
| 1 Median (Q1, Q3); n (%) | ||||
| 2 Wilcoxon rank sum test; Pearson’s Chi-squared test | ||||
6.7.4 Step 2: Crude vs adjusted estimates
crude <- glm(response ~ trt, data = trial, family = binomial)
adj <- glm(response ~ trt + age + grade + stage, data = trial, family = binomial)
tbl_merge(
list(tbl_regression(crude, exponentiate = TRUE),
tbl_regression(adj, exponentiate = TRUE)),
tab_spanner = c("**Crude**", "**Adjusted**")
)Error in `tbl_merge()`:
! The package "broom.helpers" (>= 1.20.0) is required.
6.7.5 Step 3: The change-in-estimate check
A common rule of thumb: if adjusting changes the estimate by more than 10%, confounding was present.
\[\text{Percent change} = \frac{OR_{crude} - OR_{adjusted}}{OR_{adjusted}} \times 100\]
or_crude <- exp(coef(crude)["trtDrug B"])
or_adj <- exp(coef(adj)["trtDrug B"])
round(100 * (or_crude - or_adj) / or_adj, 1)trtDrug B
5.6
Because trial is randomized, the change should be small. Randomization balances confounders on average, which is why randomized trials are the strongest design. In observational data, expect bigger changes.
6.7.6 Propensity score matching (MatchIt)
What it’s for: in observational data, treated and untreated people often differ a lot. Matching pairs each treated person with a similar untreated person, so the groups look like they came from a trial.
Question: Did a 1970s job training program (
treat) raise earnings in 1978 (re78)?
lalonde (MatchIt package) is a classic teaching dataset where the treated and comparison groups differ a lot at baseline.
library(MatchIt)
data("lalonde", package = "MatchIt")
# Step 1: How unbalanced are the groups before matching?
m0 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,
data = lalonde, method = NULL, distance = "glm")
summary(m0)$sum.all[, c("Means Treated", "Means Control", "Std. Mean Diff.")] Means Treated Means Control Std. Mean Diff.
distance 5.774355e-01 0.1822248 1.79408605
age 2.581622e+01 28.0303030 -0.30944526
educ 1.034595e+01 10.2354312 0.05496466
raceblack 8.432432e-01 0.2027972 1.76154189
racehispan 5.945946e-02 0.1421911 -0.34984254
racewhite 9.729730e-02 0.6550117 -1.88186760
married 1.891892e-01 0.5128205 -0.82630927
nodegree 7.081081e-01 0.5967366 0.24497023
re74 2.095574e+03 5619.2365064 -0.72108381
re75 1.532055e+03 2466.4844431 -0.29026291
# Step 2: Match 1 treated to 1 control on the propensity score (chance of being treated)
m1 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,
data = lalonde, method = "nearest", distance = "glm")
# Step 3: Check balance. Standardized mean differences (SMD) under 0.1 are the usual goal
summary(m1, un = FALSE)$sum.matched[, c("Means Treated", "Means Control", "Std. Mean Diff.")] Means Treated Means Control Std. Mean Diff.
distance 5.774355e-01 0.3628914 0.97393770
age 2.581622e+01 25.3027027 0.07176969
educ 1.034595e+01 10.6054054 -0.12904256
raceblack 8.432432e-01 0.4702703 1.02585928
racehispan 5.945946e-02 0.2162162 -0.66286797
racewhite 9.729730e-02 0.3135135 -0.72956754
married 1.891892e-01 0.2108108 -0.05520524
nodegree 7.081081e-01 0.6378378 0.15456488
re74 2.095574e+03 2342.1075635 -0.05045079
re75 1.532055e+03 1614.7451252 -0.02568604
Reading it: income and marital status are now balanced, but race is still badly off (SMD around 1). Simple matching paired each treated person with the closest control, but many “closest” controls were still not very close. This is the most important lesson of matching: always check balance; never assume it worked.
# Step 3b: Add a caliper, which refuses matches that are too far apart
m2 <- matchit(treat ~ age + educ + race + married + nodegree + re74 + re75,
data = lalonde, method = "nearest", distance = "glm", caliper = 0.1)
summary(m2, un = FALSE)$sum.matched[, c("Means Treated", "Means Control", "Std. Mean Diff.")] Means Treated Means Control Std. Mean Diff.
distance 0.5096023 0.4927948 0.076299118
age 25.9459459 26.1441441 -0.027700582
educ 10.4864865 10.4864865 0.000000000
raceblack 0.7387387 0.7207207 0.049558419
racehispan 0.0990991 0.1081081 -0.038095860
racewhite 0.1621622 0.1711712 -0.030398648
married 0.2072072 0.2432432 -0.092008741
nodegree 0.6486486 0.6126126 0.079264042
re74 2667.1135045 2408.5567589 0.052911159
re75 1811.2987608 1800.8709045 0.003239218
summary(m2)$nn # how many people were matched and how many were dropped Control Treated
All (ESS) 429 185
All 429 185
Matched (ESS) 111 111
Matched 111 111
Unmatched 318 74
Discarded 0 0
plot(summary(m2)) # "love plot": dots should move toward 0 after matchingNow every SMD is under 0.1. The trade-off: treated people without a close enough match were dropped, so the result describes only the matched people.
# Step 4: Estimate the effect in the matched sample, with robust standard errors
md <- match.data(m2)
fit <- lm(re78 ~ treat, data = md, weights = weights)
lmtest::coeftest(fit, vcov. = sandwich::vcovCL, cluster = ~subclass)Error in `loadNamespace()`:
! there is no package called 'sandwich'
The treat coefficient is the average difference in 1978 earnings (in dollars) between matched treated and untreated people. When tested, people in the program earned about $1,800 more, but the p-value was about 0.08 and the confidence interval included 0. A fair summary: the evidence suggests a benefit, but this sample is too small to be sure.
Watch out for: matching only balances variables you included. Unmeasured confounders can still bias results.
Learn more: gtsummary, MatchIt getting started, Batra et al., The Epidemiologist R Handbook (free online), Rothman, Epidemiology: An Introduction.
6.8 Walkthrough 6: Time series and interrupted time series
6.8.1 Time series vs survival
| Survival analysis | Time series | |
|---|---|---|
| Unit | a person | a time point (day, month) |
| Question | how long until an event? | how does a count or value change over time? |
| Example | days until death | monthly crisis calls |
6.8.2 The question
Did the UK law requiring front-seat belts (February 1983) reduce the number of drivers killed each month?
This is an interrupted time series (ITS): a policy “interrupts” the series, and we ask whether the level changed afterward, beyond the trend and seasons that were already there.
Seatbelts (built into R): monthly UK road data, January 1969 to December 1984.
6.8.3 Step 1: Look at the data
library(forecast)
autoplot(Seatbelts[, "DriversKilled"]) +
geom_vline(xintercept = 1983 + 1/12, linetype = "dashed", color = "red") +
labs(title = "UK drivers killed per month", subtitle = "Dashed line: seat belt law, Feb 1983",
x = NULL, y = "Drivers killed")6.8.4 Step 2: Separate trend and seasonality
Road deaths rise in winter every year. Decomposition splits the series into trend, seasonal pattern and leftover noise, so we do not mistake a normal seasonal dip for a policy effect.
decompose(Seatbelts[, "DriversKilled"]) |> autoplot()6.8.5 Step 3: Build a modeling dataset
sb <- tibble(
date = seq(ymd("1969-01-01"), by = "month", length.out = nrow(Seatbelts)),
deaths = as.numeric(Seatbelts[, "DriversKilled"]),
law = as.numeric(Seatbelts[, "law"]), # 0 before Feb 1983, 1 after
kms = as.numeric(Seatbelts[, "kms"]) # distance driven, a possible confounder
) |>
mutate(time = row_number(), # 1, 2, 3, ... captures the trend
month = factor(lubridate::month(date))) # captures seasons6.8.6 Step 4: Segmented regression
\[\text{deaths}_t = \beta_0 + \beta_1 \cdot \text{time}_t + \beta_2 \cdot \text{law}_t + \text{month effects} + \beta_3 \cdot \text{kms}_t\]
- \(\beta_1\): the pre-existing trend per month
- \(\beta_2\): the immediate change in level after the law (our main answer)
- month effects: the usual seasonal ups and downs
its <- lm(deaths ~ time + law + month + kms, data = sb)
tidy(its, conf.int = TRUE) |> filter(term %in% c("time", "law", "kms"))# A tibble: 3 × 7
term estimate std.error statistic p.value conf.low conf.high
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 time -0.441 0.0779 -5.66 0.0000000611 -0.594 -0.287
2 law -18.6 4.37 -4.26 0.0000329 -27.3 -10.0
3 kms 0.00816 0.00188 4.34 0.0000241 0.00445 0.0119
Interpret: when tested, the law coefficient was about -19 (95% CI about -27 to -10). That means about 19 fewer drivers were killed per month after the law, beyond what the existing downward trend, the seasons and the distance driven would predict. With about 125 deaths per month before the law, that is roughly a 15% drop.
6.8.7 Step 5: Check for autocorrelation
Time series values are usually linked to the month before (autocorrelation), which makes ordinary standard errors too small.
ggAcf(residuals(its)) # bars outside the blue lines mean leftover autocorrelation# An ARIMA model with the law as a predictor handles autocorrelation
arima_fit <- auto.arima(Seatbelts[, "DriversKilled"], xreg = Seatbelts[, "law"])
arima_fitSeries: Seatbelts[, "DriversKilled"]
Regression with ARIMA(1,0,0)(1,1,0)[12] errors
Coefficients:
ar1 sar1 drift xreg
0.3599 -0.4088 0.0048 -19.5561
s.e. 0.0710 0.0691 0.1333 7.6754
sigma^2 = 329.5: log likelihood = -776.35
AIC=1562.7 AICc=1563.04 BIC=1578.66
6.8.8 Step 6: Forecasting (bonus)
auto.arima(AirPassengers) |> forecast(h = 24) |> autoplot() +
labs(title = "Forecast of monthly airline passengers")Turn your own data into a time series with ts(df$count, start = c(2019, 1), frequency = 12) for monthly data, or frequency = 7 for daily data with a weekly pattern.
Learn more: Hyndman and Athanasopoulos, Forecasting: Principles and Practice (free online); Bernal, Cummins and Gasparrini, “Interrupted time series regression for the evaluation of public health interventions,” International Journal of Epidemiology (2017).
7 Part 6: Finding Patterns and Groups
7.1 Which method do I need?
These methods are unsupervised: there is no outcome variable. You are asking the data to show its own structure.
| Method | What it groups | Data type | Typical question |
|---|---|---|---|
| PCA | variables (columns) | numeric | “Can 20 lab values be summed up as 2 or 3 underlying dimensions?” |
| Clustering (k-means, hierarchical) | people or units (rows) | numeric, or mixed with Gower distance | “Are there groups of counties with similar health profiles?” |
| LCA | people (rows) | categorical (yes/no, multiple choice) | “Are there hidden subgroups of people with similar patterns of adversity?” |
The key difference: PCA shrinks many variables into a few. Clustering and LCA sort people into groups. LCA is the model-based cousin of clustering for categorical answers.
7.2 Walkthrough 7: Principal component analysis (PCA)
Principal comes from the Latin principalis, “first” or “chief.” The principal components are the chief directions of variation in the data.
7.2.1 The question
The
USArrestsdata has four measures for each US state. Can they be summarized with fewer dimensions, and which states are similar?
| Variable | Meaning |
|---|---|
Murder, Assault, Rape |
arrests per 100,000 residents (1973) |
UrbanPop |
percent of the population living in cities |
7.2.2 Step 1: Why PCA? Check the correlations
PCA is useful when variables are correlated, because correlated variables carry overlapping information.
round(cor(USArrests), 2) Murder Assault UrbanPop Rape
Murder 1.00 0.80 0.07 0.56
Assault 0.80 1.00 0.26 0.67
UrbanPop 0.07 0.26 1.00 0.41
Rape 0.56 0.67 0.41 1.00
Murder, Assault and Rape are strongly correlated, so they probably reflect one shared “crime level” dimension.
7.2.3 Step 2: Scale the variables
Why: Assault values are in the hundreds while Murder is under 20. Without scaling, PCA would treat Assault as most important just because its numbers are bigger. scale. = TRUE puts every variable on the same footing (mean 0, standard deviation 1).
pca <- prcomp(USArrests, scale. = TRUE)7.2.4 Step 3: How many components to keep?
summary(pca) # "Proportion of Variance" for each PCImportance of components:
PC1 PC2 PC3 PC4
Standard deviation 1.5749 0.9949 0.59713 0.41645
Proportion of Variance 0.6201 0.2474 0.08914 0.04336
Cumulative Proportion 0.6201 0.8675 0.95664 1.00000
screeplot(pca, type = "lines", main = "Scree plot")Reading it: each principal component (PC) explains a share of the total variation. Common rules: keep components until you reach about 80% cumulative variance, or keep those before the “elbow” where the scree plot flattens. Here PC1 and PC2 together explain about 87%, so two components summarize four variables well.
7.2.5 Step 4: Interpret the loadings
Loadings show how much each original variable contributes to each component.
round(pca$rotation[, 1:2], 2) PC1 PC2
Murder -0.54 -0.42
Assault -0.58 -0.19
UrbanPop -0.28 0.87
Rape -0.54 0.17
- PC1 has similar-sized loadings on Murder, Assault and Rape: an overall crime dimension.
- PC2 is dominated by UrbanPop: an urbanization dimension.
The sign (+ or -) of a whole component is arbitrary; only the pattern within a component matters.
7.2.6 Step 5: Plot the states
scores <- as_tibble(pca$x) |> mutate(state = rownames(USArrests))
ggplot(scores, aes(PC1, PC2, label = state)) +
geom_hline(yintercept = 0, color = "gray80") + geom_vline(xintercept = 0, color = "gray80") +
geom_text(size = 3) +
labs(title = "US states on the first two principal components",
x = "PC1 (overall crime)", y = "PC2 (urbanization)")biplot(pca, scale = 0, cex = 0.6) # states plus arrows for each variableStates close together have similar profiles. PC scores can also be used as predictors in a regression when you have too many correlated variables.
7.3 Walkthrough 8: Clustering (grouping people or places)
7.3.1 The question
Are there natural groups of US states with similar crime and urbanization profiles?
How clustering works: it measures how far apart each pair of rows is (a distance), then puts close rows in the same group. Two main approaches:
| Approach | How it works | Good for |
|---|---|---|
| Hierarchical | merges the closest rows step by step, building a tree (dendrogram) | seeing structure at every level; small to medium data |
| k-means | you pick k groups; it moves k centers until each row is nearest its own center | larger data; when you have an idea of k |
7.3.2 Step 1: Prepare and scale
The same scaling reason as PCA applies: distances would be dominated by the variable with the biggest numbers.
x <- scale(USArrests) # rows = states, columns = scaled variables
d <- dist(x) # Euclidean distance between every pair of states7.3.3 Step 2: Hierarchical clustering
hc <- hclust(d, method = "ward.D2") # Ward's method makes compact, similar-sized groups
plot(hc, cex = 0.6, main = "Dendrogram of US states", xlab = "", sub = "")
rect.hclust(hc, k = 4, border = 2:5) # draw boxes around 4 groupshc_groups <- cutree(hc, k = 4)
table(hc_groups)hc_groups
1 2 3 4
7 12 19 12
Reading a dendrogram: states that join low on the tree are very similar. Cutting the tree at a height gives the groups. Long vertical lines before a merge mean the groups being joined are quite different, which suggests a good place to cut.
7.3.4 Step 3: Choosing the number of groups (k)
Two common checks:
- Elbow method: total within-group spread for each k. Look for where adding another group stops helping much.
- Silhouette width: how well each row fits its own group vs the next closest group, from -1 to 1. Higher average is better.
library(cluster)
set.seed(123)
k_check <- tibble(k = 2:8) |>
mutate(
within_ss = map_dbl(k, \(k) kmeans(x, centers = k, nstart = 25)$tot.withinss),
silhouette = map_dbl(k, \(k) {
km <- kmeans(x, centers = k, nstart = 25)
mean(silhouette(km$cluster, d)[, "sil_width"])
})
)
k_check# A tibble: 7 × 3
k within_ss silhouette
<int> <dbl> <dbl>
1 2 103. 0.408
2 3 78.3 0.309
3 4 56.4 0.340
4 5 48.9 0.303
5 6 42.8 0.290
6 7 38.3 0.289
7 8 33.9 0.260
ggplot(k_check, aes(k, within_ss)) + geom_line() + geom_point() +
labs(title = "Elbow plot", y = "Total within-group sum of squares")There is rarely one perfect k. Choose a value supported by these checks and that gives groups you can describe in plain language.
7.3.5 Step 4: k-means
set.seed(123) # k-means starts randomly, so set a seed
km <- kmeans(x, centers = 4, nstart = 25) # nstart = 25 tries 25 starts and keeps the best
km$size[1] 16 13 8 13
7.3.6 Step 5: Profile the groups (the most important step)
A cluster number means nothing until you describe it. Go back to the original, unscaled values:
profiles <- USArrests |>
mutate(cluster = factor(km$cluster)) |>
group_by(cluster) |>
summarise(states = n(), across(Murder:Rape, \(v) round(mean(v), 1)))
profiles# A tibble: 4 × 6
cluster states Murder Assault UrbanPop Rape
<fct> <int> <dbl> <dbl> <dbl> <dbl>
1 1 16 5.7 139. 73.9 18.8
2 2 13 10.8 257. 76 33.2
3 3 8 13.9 244. 53.8 21.4
4 4 13 3.6 78.5 52.1 12.2
Then give each group a descriptive name. When tested, the four groups were roughly: high murder, mostly rural (mainly Southern states), low crime, rural, moderate crime, urban, and high crime, highly urban. Look at the member states to check that each name makes sense:
split(rownames(USArrests), km$cluster)$`1`
[1] "Connecticut" "Delaware" "Hawaii" "Indiana"
[5] "Kansas" "Massachusetts" "New Jersey" "Ohio"
[9] "Oklahoma" "Oregon" "Pennsylvania" "Rhode Island"
[13] "Utah" "Virginia" "Washington" "Wyoming"
$`2`
[1] "Alaska" "Arizona" "California" "Colorado" "Florida"
[6] "Illinois" "Maryland" "Michigan" "Missouri" "Nevada"
[11] "New Mexico" "New York" "Texas"
$`3`
[1] "Alabama" "Arkansas" "Georgia" "Louisiana"
[5] "Mississippi" "North Carolina" "South Carolina" "Tennessee"
$`4`
[1] "Idaho" "Iowa" "Kentucky" "Maine"
[5] "Minnesota" "Montana" "Nebraska" "New Hampshire"
[9] "North Dakota" "South Dakota" "Vermont" "West Virginia"
[13] "Wisconsin"
7.3.7 Step 6: Visualize clusters on the PCA axes
scores |>
mutate(cluster = factor(km$cluster)) |>
ggplot(aes(PC1, PC2, color = cluster, label = state)) +
geom_text(size = 3) +
labs(title = "k-means clusters shown on PCA axes", color = "Cluster")7.3.8 Step 7: A reality check with iris
Clustering always produces groups, even in random noise. Testing it on data where the true groups are known shows how well it works:
set.seed(1)
iris_km <- kmeans(scale(iris[, 1:4]), centers = 3, nstart = 25)
table(Cluster = iris_km$cluster, Species = iris$Species) Species
Cluster setosa versicolor virginica
1 0 39 14
2 0 11 36
3 50 0 0
Setosa is found perfectly, but versicolor and virginica overlap, because those two species really do look alike.
7.3.9 Mixed data types: Gower distance and PAM
Health data usually mixes numbers (age, BMI) with categories (sex, insurance). Euclidean distance only works for numbers. Gower distance handles both, and PAM (partitioning around medoids) clusters using any distance.
cars_mixed <- mtcars |>
mutate(am = factor(am, labels = c("auto", "manual")), cyl = factor(cyl)) |>
select(mpg, hp, wt, am, cyl)
gower <- daisy(cars_mixed, metric = "gower")
pam_fit <- pam(gower, k = 3, diss = TRUE)
cars_mixed |>
mutate(cluster = factor(pam_fit$clustering)) |>
group_by(cluster) |>
summarise(n = n(), mpg = mean(mpg), hp = mean(hp), pct_manual = mean(am == "manual"))# A tibble: 3 × 5
cluster n mpg hp pct_manual
<fct> <int> <dbl> <dbl> <dbl>
1 1 10 20.7 111 0.3
2 2 8 28.1 81.9 1
3 3 14 15.1 209. 0.143
rownames(cars_mixed)[pam_fit$id.med] # the "medoid": the most typical car in each group[1] "Hornet 4 Drive" "Fiat X1-9" "Merc 450SLC"
Watch out for:
- Always scale numeric variables (Gower does this for you).
- Set a seed so k-means gives the same answer each time.
- Clusters are descriptions, not proof that the groups are real. Check stability by re-running with a different seed or a different method.
Learn more: James et al., An Introduction to Statistical Learning, Chapter 12 (free online); cluster package; Boehmke, UC Business Analytics R guide to k-means clustering.
7.4 Walkthrough 9: Latent class analysis (LCA)
Latent comes from the Latin latere, “to lie hidden.” LCA assumes there are hidden groups (classes) we cannot see directly, and that each person’s pattern of answers depends on which hidden group they are in.
7.4.1 The question
Seven pathologists each rated the same 118 cervical tissue slides as showing carcinoma or not. There is no gold standard. Can LCA uncover the slides’ hidden true status, and how accurate is each pathologist?
This is a classic medical use of LCA: estimating disease status and test accuracy when no perfect test exists.
carcinoma (poLCA package): columns A to G are the seven pathologists. Each rating is coded 1 = no carcinoma, 2 = carcinoma.
7.4.2 Step 1: Look at the data
library(poLCA)
data(carcinoma)
head(carcinoma) A B C D E F G
1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1
3 1 1 1 1 1 1 1
4 1 1 1 1 1 1 1
5 1 1 1 1 1 1 1
6 1 1 1 1 1 1 1
carcinoma |> summarise(across(everything(), \(v) mean(v == 2))) # share rated "carcinoma" by each A B C D E F G
1 0.559322 0.6694915 0.3813559 0.2711864 0.6016949 0.2118644 0.559322
The pathologists disagree a lot: some call far more slides cancer than others.
7.4.3 Step 2: Fit models with 1 to 4 classes
LCA needs you to try several numbers of classes and compare. nrep = 10 runs each model from 10 random starts, so it does not get stuck on a poor answer.
f <- cbind(A, B, C, D, E, F, G) ~ 1 # ~ 1 means no predictors of class membership
set.seed(123)
fits <- map(1:4, \(k) poLCA(f, carcinoma, nclass = k, nrep = 10, verbose = FALSE))
tibble(classes = 1:4,
BIC = map_dbl(fits, "bic"),
AIC = map_dbl(fits, "aic"))# A tibble: 4 × 3
classes BIC AIC
<int> <dbl> <dbl>
1 1 1082. 1063.
2 2 706. 665.
3 3 697. 633.
4 4 726. 641.
Choosing the number of classes:
- BIC (Bayesian information criterion): lower is better, and it penalizes extra classes. It is the most commonly used guide.
- Also ask whether each class makes sense and is not tiny (under about 5% of people).
7.4.4 Step 3: Interpret the chosen model
lca <- fits[[3]] # pick the model your BIC and judgment support
round(lca$P, 2) # share of slides in each class[1] 0.37 0.44 0.18
# Probability each pathologist says "carcinoma" within each class
map_dfr(lca$probs, \(m) tibble(class = paste0("class_", 1:nrow(m)), p_carcinoma = round(m[, 2], 2)),
.id = "pathologist") |>
pivot_wider(names_from = class, values_from = p_carcinoma)# A tibble: 7 × 4
pathologist class_1 class_2 class_3
<chr> <dbl> <dbl> <dbl>
1 A 0.06 1 0.51
2 B 0.14 0.98 1
3 C 0 0.86 0
4 D 0 0.59 0.06
5 E 0.06 1 0.75
6 F 0 0.48 0
7 G 0 1 0.63
Reading it: when tested, BIC was lowest for 3 classes, and they had clear meanings:
| Pattern | Share of slides | What it looks like |
|---|---|---|
| Clearly no cancer | about 37% | almost no pathologist says carcinoma |
| Clearly cancer | about 44% | nearly every pathologist says carcinoma |
| Ambiguous | about 18% | pathologists A, B, E and G usually say carcinoma; C, D and F usually do not |
In the “clearly cancer” class, each pathologist’s probability of saying “carcinoma” is their sensitivity (how often they catch true cancer). In the “clearly no cancer” class, 1 minus that probability is their specificity. Pathologists D and F have low sensitivity: they miss about half of the clear cancers. The ambiguous class shows slides where experts genuinely disagree, which a single “gold standard” pathologist would hide.
Class numbers are arbitrary and can swap between runs, so always name classes by their pattern, never by their number.
7.4.5 Step 4: Assign each slide to a class
carcinoma |>
mutate(class = lca$predclass, # most likely class
certainty = round(apply(lca$posterior, 1, max), 2)) |> # how sure the model is
count(A, B, C, D, E, F, G, class, certainty, name = "slides") |> # each unique rating pattern
arrange(class) A B C D E F G class certainty slides
1 1 1 1 1 1 1 1 1 1.00 34
2 1 1 1 1 2 1 1 1 1.00 2
3 1 2 1 1 1 1 1 1 0.86 6
4 2 1 1 1 1 1 1 1 1.00 2
5 2 1 2 1 2 1 2 2 1.00 1
6 2 2 1 1 2 2 2 2 1.00 1
7 2 2 1 2 2 1 2 2 0.88 2
8 2 2 1 2 2 2 2 2 1.00 3
9 2 2 2 1 2 1 2 2 1.00 13
10 2 2 2 1 2 2 2 2 1.00 5
11 2 2 2 2 2 1 2 2 1.00 10
12 2 2 2 2 2 2 2 2 1.00 16
13 1 2 1 1 1 1 2 3 1.00 1
14 1 2 1 1 2 1 1 3 0.90 4
15 1 2 1 1 2 1 2 3 1.00 5
16 2 2 1 1 1 1 1 3 0.74 2
17 2 2 1 1 1 1 2 3 1.00 1
18 2 2 1 1 2 1 1 3 0.99 2
19 2 2 1 1 2 1 2 3 0.76 7
20 2 2 1 2 1 1 2 3 1.00 1
Posterior probabilities close to 1 mean the model is confident. Many values near 0.5 mean the classes are poorly separated.
7.4.6 Applying LCA to your own data
The same steps work for survey items such as yes/no adversity questions:
- Recode every item to 1, 2, 3 (poLCA does not accept 0 or missing codes like 7 and 9).
- Fit 1 to about 6 classes with
nrepof 10 or more. - Compare BIC, class sizes and interpretability.
- Name each class by its answer pattern (“high financial strain, low social support”).
- Use class membership as an exposure or outcome in later regression models.
Learn more: Linzer and Lewis, “poLCA: An R Package for Polytomous Variable Latent Class Analysis,” Journal of Statistical Software (2011); Weller, Bowen and Faubert, “Latent Class Analysis: A Guide to Best Practice,” Journal of Black Psychology (2020).
8 Part 7: Sharing Your Work
8.1 Exporting plots and tables
ggsave("figure1.png", plot = base, width = 7, height = 5, dpi = 300) # poster quality
ggsave("figure1.pdf", plot = base, width = 7, height = 5)
write_csv(cohort, "cohort.csv")
library(gt)
mtcars |> head() |> gt() |> tab_header(title = "First six cars") |> gtsave("table.html")
tbl_summary(trial) |> as_flex_table() |> flextable::save_as_docx(path = "table1.docx")8.2 Making your own Quarto documents
A .qmd file has three parts:
- YAML header between
---lines: title, format, options - Text written in markdown:
**bold**,*italic*,# Heading,[link](url) - Code chunks that start with three backticks and
{r}
Chunk options go at the top of a chunk with #|:
| Option | Does |
|---|---|
#| echo: false |
hide code, show output |
#| eval: false |
show code, do not run |
#| include: false |
run silently (good for setup) |
#| warning: false |
hide warnings |
#| fig-cap: "Caption" |
figure caption |
#| fig-width: 7 |
figure size |
#| label: fig-scatter |
lets you cross-reference with @fig-scatter |
Output formats in the YAML:
format: html # web page
format: docx # Word
format: pdf # needs tinytex: quarto install tinytex
format: revealjs # slidesFor slides, each ## heading is a new slide. Images: {width=60%}. Render with the Render button or quarto render file.qmd in the terminal. Use here() for paths so the project works on any computer, and use RStudio Projects to keep each study in its own folder.
Learn more: Quarto guide, Quarto slides, Wickham et al., R for Data Science, 2e (free online)
8.3 R Shiny apps
What it’s for: interactive web apps where users pick options and plots update. Shiny needs a live R session, so this code is shown, not run. Paste it into a file called app.R and click Run App.
Every app has a UI (what users see), a server (what R calculates), and shinyApp() to join them.
library(shiny); library(ggplot2)
ui <- fluidPage(
titlePanel("Explore mtcars"),
sidebarLayout(
sidebarPanel(
selectInput("xvar", "X variable", choices = names(mtcars), selected = "wt"),
selectInput("yvar", "Y variable", choices = names(mtcars), selected = "mpg"),
sliderInput("size", "Point size", min = 1, max = 6, value = 3),
checkboxInput("trend", "Add trend line", value = FALSE)
),
mainPanel(plotOutput("scatter"), tableOutput("summary"))
)
)
server <- function(input, output) {
output$scatter <- renderPlot({
p <- ggplot(mtcars, aes(.data[[input$xvar]], .data[[input$yvar]])) +
geom_point(size = input$size) + theme_minimal()
if (input$trend) p <- p + geom_smooth(method = "lm")
p
})
output$summary <- renderTable({
data.frame(stat = c("mean", "sd"),
value = c(mean(mtcars[[input$yvar]]), sd(mtcars[[input$yvar]])))
})
}
shinyApp(ui, server)Inputs (input$name) come from the UI. Outputs use matching pairs: plotOutput() with renderPlot(), tableOutput() with renderTable(), textOutput() with renderText(). Share free at shinyapps.io with rsconnect::deployApp().
Learn more: Shiny tutorials, Wickham, Mastering Shiny (free online)
9 Part 8: Common Errors and Fixes
| Error message | Usual cause | Fix |
|---|---|---|
could not find function "x" |
package not loaded | library(pkg) |
there is no package called 'x' |
not installed | install.packages("x") |
object 'x' not found |
typo, or column used outside a dplyr verb | check spelling, use df$x |
non-numeric argument to binary operator |
numbers stored as text | as.numeric() |
arguments imply differing number of rows |
vectors of different lengths | check length() |
unexpected symbol |
missing comma or parenthesis | check the line above |
unused argument for a function you know works |
another package has a function with the same name (for example data.table’s month() hides lubridate’s) |
write package::function(), such as lubridate::month() |
NAs introduced by coercion |
text that is not a number | inspect with unique() |
Result is all NA |
missing values | na.rm = TRUE |
| Rows multiplied after join | duplicate keys | check count(df, id) |> filter(n > 1) |
Error in plot.new(): figure margins too large |
plot pane too small | enlarge pane |
ggplot + error |
+ placed at start of line |
put + at the end of the line |
General tips: read the last line of the error first, restart R (Session, Restart R) when things act strange, and use ?function_name for help.
10 Sources
- Wickham, Çetinkaya-Rundel, and Grolemund. R for Data Science, 2e. https://r4ds.hadley.nz
- Wickham. ggplot2: Elegant Graphics for Data Analysis, 3e. https://ggplot2-book.org
- Batra et al. The Epidemiologist R Handbook. https://epirhandbook.com
- Lumley. Complex Surveys: A Guide to Analysis Using R. Wiley, 2010.
- Hyndman and Athanasopoulos. Forecasting: Principles and Practice, 3e. https://otexts.com/fpp3/
- van Buuren. Flexible Imputation of Missing Data, 2e. https://stefvanbuuren.name/fimd/
- James et al. An Introduction to Statistical Learning. https://www.statlearning.com
- Wickham. Mastering Shiny. https://mastering-shiny.org
- CDC NHANES Tutorials. https://wwwn.cdc.gov/nchs/nhanes/tutorials/
- Quarto documentation. https://quarto.org
- Package documentation on CRAN and tidyverse.org, linked in each section