library(r02pro) # the gm data
library(dplyr)
library(tidyr)GPH-GU 2182: Statistical Programming in R · Fall 2026
New York University · School of Global Public Health
2026-10-07
group_by() + summarize().count() and weighted counts.left_join(), inner_join(), anti_join().pivot_longer() & pivot_wider().Last week’s verbs kept data at the row level. Public health questions usually need group-level answers:
summarize(): Collapse to One RowWithout grouping, summarize() collapses the whole table to a single row:
# A tibble: 1 × 3
mean_le sd_le n
<dbl> <dbl> <int>
1 70.2 8.44 195
n() counts rows and takes no arguments.group_by(): One Row Per Groupgroup_by() changes what “everything” means for the next verbs:
# A tibble: 6 × 3
continent mean_le n_countries
<chr> <dbl> <int>
1 Africa 61.2 50
2 Americas 74.4 33
3 Asia 72.6 45
4 Europe 77.5 38
5 Oceania 67.4 10
6 <NA> 67.9 19
One row per continent: the group becomes the unit of analysis.
# A tibble: 12 × 3
continent year mean_le
<chr> <dbl> <dbl>
1 Africa 1998 56.3
2 Africa 2008 61.2
3 Americas 1998 72.4
4 Americas 2008 74.4
# ℹ 8 more rows
A grouped tibble stays grouped! Later verbs operate within groups until you ungroup() or use .groups = "drop", which returns an ordinary tibble (and silences the message).
count(): The Fast Path for Frequencies# A tibble: 6 × 2
continent n
<chr> <int>
1 Africa 50
2 Americas 36
3 Asia 46
4 Europe 38
5 Oceania 12
6 <NA> 54
count(x) is shorthand for group_by(x) |> summarize(n = n()).
count(sort = TRUE): Largest Group Firstgm, keep 2008 rows with non-missing child_mortality.continent.mean_cm (mean child mortality), max_cm (maximum), and n_countries with n().mean_cm.filter before group_by.summarize().Real public health data arrives as separate tables:
To analyze patients by borough, the tables must be joined on the shared key clinic_id.
left_join(): Keep All Rows on the Left# A tibble: 4 × 4
patient_id age clinic_id borough
<chr> <dbl> <chr> <chr>
1 P1 34 C1 Brooklyn
2 P2 58 C2 Queens
3 P3 41 C1 Brooklyn
4 P4 29 C3 <NA>
NA.inner_join() and anti_join()inner_join(): matches only# A tibble: 3 × 4
patient_id age clinic_id borough
<chr> <dbl> <chr> <chr>
1 P1 34 C1 Brooklyn
2 P2 58 C2 Queens
3 P3 41 C1 Brooklyn
Keeps rows present in both tables.
Tip
Before trusting a join, count() the key in both tables: duplicated keys multiply rows!
Your worksheet defines visits (patient visits) and lab_results (test outcomes).
left_join() the two tables by visit_id; how many rows result?anti_join() to list visits with no lab result on file.inner_join() and then group_by(clinic) |> summarize(mean_glucose = mean(glucose)).by = "visit_id" spelled explicitly.anti_join result should surprise you: which visits are they?Untidy (wide): one row per patient, one column per visit
# A tibble: 2 × 4
patient bp_visit1 bp_visit2 bp_visit3
<chr> <dbl> <dbl> <dbl>
1 P1 142 138 131
2 P2 129 125 122
Tidy (long): one row per patient-visit (next slide).
pivot_longer(): Wide → Longcols: which columns to stack (select-style helpers work!).names_to: new column holding the old column names.values_to: new column holding the old cell values.names_prefix: strip repeated text from the names.Why? ggplot2 and group_by() need long data: one row per observation.
pivot_wider(): Long → WideThe inverse: spread a name-value pair back into columns (great for human-readable tables):
pivot_wider() for Summary Tables# A tibble: 6 × 3
continent `1998` `2008`
<chr> <dbl> <dbl>
1 Africa 56.3 61.2
2 Americas 72.4 74.4
3 Asia 69.5 72.6
4 Europe 74.9 77.5
5 Oceania 66.4 67.4
6 <NA> 66.0 67.9
drop_na(): Explicit Missing-Row Removal# A tibble: 221 × 33
country year smoking_female smoking_male lungcancer_newcases_female
<chr> <dbl> <dbl> <dbl> <dbl>
1 Albania 2001 4 40.5 11.2
2 Albania 2004 4 40.5 11
# ℹ 219 more rows
# A tibble: 8,973 × 33
country year smoking_female smoking_male lungcancer_newcases_female
<chr> <dbl> <dbl> <dbl> <dbl>
1 Albania 1999 4 NA 11.1
2 Albania 2000 NA NA 10.8
# ℹ 8,971 more rows
Equivalent to chained filter(!is.na(...)) calls, but reads more clearly in pipelines.
Your worksheet defines bp_wide (blood pressure over 3 visits).
bp_wide into long form bp_long (visit, bp columns; strip the "bp_" prefix).bp_long by visit and summarize the mean BP per visit.bp_long back to wide and confirm it matches the original.starts_with("bp_") selects the pivot columns.# Which continents improved life expectancy most between 1998 and 2008?
gm |>
filter(year %in% c(1998, 2008)) |>
drop_na(life_expectancy) |>
group_by(continent, year) |>
summarize(mean_le = mean(life_expectancy), .groups = "drop") |>
pivot_wider(names_from = year, values_from = mean_le,
names_prefix = "y") |>
mutate(gain = y2008 - y1998) |>
arrange(desc(gain))# A tibble: 6 × 4
continent y1998 y2008 gain
<chr> <dbl> <dbl> <dbl>
1 Africa 56.3 61.2 4.90
2 Asia 69.5 72.6 3.06
3 Europe 74.9 77.5 2.51
4 Americas 72.4 74.4 2.02
# ℹ 2 more rows
Seven verbs, one readable story: filter → clean → group → summarize → reshape → derive → sort.
An AI assistant merged medication records onto patients:
[1] 4
[1] 8
It ran without errors, but the patient count doubled: patients with multiple prescriptions now appear once per prescription, so every later average is silently weighted by prescription count.
Audit protocol for every join:
nrow() before and after: did the row count change? Why?count(patient_id) |> filter(n > 1): are keys unique where you assumed?anti_join() both directions: what failed to match?Important
An AI can write a syntactically perfect join that is statistically wrong. The audit is your job.
stringr: pattern matching & regex basics.forcats for factors; lubridate for dates.Questions? Office hours are listed on the syllabus page, or email anytime.