Week 6: Advanced Wrangling, Joins & Tidy Data

GPH-GU 2182: Statistical Programming in R · Fall 2026

Yang Feng, PhD

New York University · School of Global Public Health

2026-10-07

Welcome to Week 6!

Today’s Roadmap

  1. Grouped Summaries: group_by() + summarize().
  2. Counting: count() and weighted counts.
  3. Joining Tables: left_join(), inner_join(), anti_join().
  4. Tidy Data: pivot_longer() & pivot_wider().
  5. AI Corner: Join key traps in AI-generated code.

Today’s Milestones

  • Homework 6: Released today.
  • Looking Ahead: Quiz 3 (Weeks 5–6) takes place in Week 7.

Cycle 1: Grouped Summaries

From Rows to Summaries

Last week’s verbs kept data at the row level. Public health questions usually need group-level answers:

  • What is the average life expectancy per continent?
  • How many countries per region exceeded a smoking threshold?
  • What is each hospital’s median wait time?
library(r02pro)   # the gm data
library(dplyr)
library(tidyr)

summarize(): Collapse to One Row

Without grouping, summarize() collapses the whole table to a single row:

gm |>
  filter(year == 2008, !is.na(life_expectancy)) |>
  summarize(mean_le = mean(life_expectancy),
            sd_le   = sd(life_expectancy),
            n       = n())
# A tibble: 1 × 3
  mean_le sd_le     n
    <dbl> <dbl> <int>
1    70.2  8.44   195
  • Each argument creates one column; the right side must return one value.
  • n() counts rows and takes no arguments.

group_by(): One Row Per Group

group_by() changes what “everything” means for the next verbs:

gm |>
  filter(year == 2008, !is.na(life_expectancy)) |>
  group_by(continent) |>
  summarize(mean_le = mean(life_expectancy),
            n_countries = n())
# 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.

Grouping by Multiple Variables

gm |>
  filter(year %in% c(1998, 2008), !is.na(life_expectancy)) |>
  group_by(continent, year) |>
  summarize(mean_le = mean(life_expectancy), .groups = "drop")
# 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
  • One row per continent × year combination.

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

# How many countries per continent in 2008?
gm |> filter(year == 2008) |> count(continent)
# 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 First

gm |> filter(year == 2008) |> count(continent, sort = TRUE)
# A tibble: 6 × 2
  continent     n
  <chr>     <int>
1 <NA>         54
2 Africa       50
3 Asia         46
4 Europe       38
5 Americas     36
6 Oceania      12

👥 Paired Exercise 1: Continental Report Card (10 min)

Task

  1. From gm, keep 2008 rows with non-missing child_mortality.
  2. Group by continent.
  3. Summarize: mean_cm (mean child mortality), max_cm (maximum), and n_countries with n().
  4. Arrange the result from highest to lowest mean_cm.

Checklist

  • filter before group_by.
  • Three summary columns in one summarize().
  • Which continent carries the highest burden?

Cycle 2: Joining Tables

Why Joins? Data Lives in Pieces

Real public health data arrives as separate tables:

patients <- tibble(
  patient_id = c("P1", "P2", "P3", "P4"),
  age        = c(34, 58, 41, 29),
  clinic_id  = c("C1", "C2", "C1", "C3")
)

clinics <- tibble(
  clinic_id = c("C1", "C2"),
  borough   = c("Brooklyn", "Queens")
)

To analyze patients by borough, the tables must be joined on the shared key clinic_id.

left_join(): Keep All Rows on the Left

patients |> left_join(clinics, by = "clinic_id")
# 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>    
  • Every patient is kept; unmatched keys get NA.
  • The workhorse join for adding context columns to a primary table.

inner_join() and anti_join()

inner_join(): matches only

patients |>
  inner_join(clinics, by = "clinic_id")
# 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.

anti_join(): the leftovers

patients |>
  anti_join(clinics, by = "clinic_id")
# A tibble: 1 × 3
  patient_id   age clinic_id
  <chr>      <dbl> <chr>    
1 P4            29 C3       

Keeps left rows with no match: your data-quality audit tool!

Tip

Before trusting a join, count() the key in both tables: duplicated keys multiply rows!

👥 Paired Exercise 2: Lab Results Lookup (10 min)

Task

Your worksheet defines visits (patient visits) and lab_results (test outcomes).

  1. left_join() the two tables by visit_id; how many rows result?
  2. Use anti_join() to list visits with no lab result on file.
  3. Use inner_join() and then group_by(clinic) |> summarize(mean_glucose = mean(glucose)).

Checklist

  • by = "visit_id" spelled explicitly.
  • anti_join result should surprise you: which visits are they?
  • Cycle 1 + Cycle 2 skills combine in step 3!

Cycle 3: Tidy Data & Pivoting

What Is Tidy Data?

  1. Every column is a variable.
  2. Every row is an observation.
  3. Every cell is a single value.

Untidy (wide): one row per patient, one column per visit

bp_wide <- tibble(patient   = c("P1", "P2"),
                  bp_visit1 = c(142, 129),
                  bp_visit2 = c(138, 125),
                  bp_visit3 = c(131, 122))
bp_wide
# 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 → Long

bp_long <- bp_wide |>
  pivot_longer(cols = starts_with("bp_"),
               names_to = "visit",
               values_to = "bp",
               names_prefix = "bp_")
bp_long
# A tibble: 6 × 3
  patient visit     bp
  <chr>   <chr>  <dbl>
1 P1      visit1   142
2 P1      visit2   138
3 P1      visit3   131
4 P2      visit1   129
5 P2      visit2   125
6 P2      visit3   122
  • cols: 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 → Wide

The inverse: spread a name-value pair back into columns (great for human-readable tables):

bp_long |>
  pivot_wider(names_from = visit, values_from = bp)
# A tibble: 2 × 4
  patient visit1 visit2 visit3
  <chr>    <dbl>  <dbl>  <dbl>
1 P1         142    138    131
2 P2         129    125    122

pivot_wider() for Summary Tables

# Classic use: a summary table with one column per year
gm |>
  filter(year %in% c(1998, 2008), !is.na(life_expectancy)) |>
  group_by(continent, year) |>
  summarize(mean_le = mean(life_expectancy), .groups = "drop") |>
  pivot_wider(names_from = year, values_from = mean_le)
# 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

# Drop rows missing ANY column
gm |> drop_na()
# 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
# Drop rows missing specific columns only (usual practice)
gm |> drop_na(life_expectancy, sugar)
# 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.

👥 Paired Exercise 3: Reshaping a BP Study (10 min)

Task

Your worksheet defines bp_wide (blood pressure over 3 visits).

  1. Pivot bp_wide into long form bp_long (visit, bp columns; strip the "bp_" prefix).
  2. Group bp_long by visit and summarize the mean BP per visit.
  3. Pivot bp_long back to wide and confirm it matches the original.

Checklist

  • starts_with("bp_") selects the pivot columns.
  • Is mean BP falling across visits?
  • Round-trip pivots are a great self-check!

Cycle 4: Integration + AI Corner

A Full Mini-Analysis, End to End

# 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.

AI Corner: The Join That Quietly Doubled the Data

An AI assistant merged medication records onto patients:

prescriptions <- tibble(
  patient_id = c("P1", "P1", "P2", "P2", "P3", "P3", "P4", "P4"),
  drug       = c("metformin", "lisinopril", "statin", "aspirin",
                 "metformin", "statin", "aspirin", "insulin")
)
nrow(patients)
[1] 4
patients |> left_join(prescriptions, by = "patient_id") |> nrow()
[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.

AI Corner: Auditing Every Join

Audit protocol for every join:

  1. nrow() before and after: did the row count change? Why?
  2. count(patient_id) |> filter(n > 1): are keys unique where you assumed?
  3. 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.

Wrap-Up & Next Steps

Before We Meet Again

📌 To Do

  • Homework 6: due date on the course website.
  • Read: R02Pro Ch 10, 3.6, 3.11 (strings, factors, dates).
  • Push today’s worksheet to GitHub.

🔭 Week 7

  • 📝 Quiz 3 (covers Weeks 5–6) at end of class.
  • stringr: pattern matching & regex basics.
  • forcats for factors; lubridate for dates.

Questions? Office hours are listed on the syllabus page, or email anytime.