Week 5: Data Wrangling with dplyr & Pipes

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

Yang Feng, PhD

New York University · School of Global Public Health

2026-09-30

Welcome to Week 5!

Today’s Roadmap

  1. The Pipe (|>): Readable multi-step pipelines.
  2. Row Operations: filter() and arrange().
  3. Column Operations: select() and rename().
  4. Creating Variables: mutate() for new columns.
  5. AI Corner: Auditing AI-written pipelines.

Today’s Milestones

  • Homework 5: Released today (dplyr wrangling).
  • 📝 Quiz 2: Last 30 minutes of class (covers Weeks 3–4).

Cycle 1: Pipes & Filtering Rows

Why Data Wrangling?

Analysts spend 50–80% of their time preparing data, not modeling it.

  • Raw public health data is messy: inconsistent units, irrelevant columns, impossible values, mixed granularities.
  • dplyr gives you a small vocabulary of verbs, each doing one thing well:
Verb Question it answers
filter() Which rows do I keep?
arrange() In what order should rows appear?
select() Which columns do I keep?
rename() What should columns be called?
mutate() What new columns do I need?

Today’s Dataset: Global Health (gm)

The gm dataset from the r02pro package tracks health indicators for world countries over time.

library(r02pro)
library(dplyr)

dim(gm)   # rows, columns
[1] 65531    33
  • country, continent, year, population
  • life_expectancy, child_mortality, sugar, food_supply
  • smoking_male, smoking_female, GDP_per_capita, HDI

One row = one country in one year.

The Native Pipe |>

The pipe takes the object on its left and passes it as the first argument to the function on its right.

Nested (hard to read)

head(filter(gm, year == 2008), 3)

Read from the inside out. 😵

Piped (reads like a recipe)

gm |>
  filter(year == 2008) |>
  head(3)

Read top to bottom: take gm, then filter, then show 3 rows.

identical(head(filter(gm, year == 2008), 3), gm |> filter(year == 2008) |> head(3))
[1] TRUE

Tip

Type |> quickly with Cmd/Ctrl + Shift + M (after enabling the native pipe in RStudio: Tools → Global Options → Code → “Use native pipe operator”).

filter(): Keeping Rows That Match

filter() keeps rows where a logical condition is TRUE (the same logicals you built in Week 2!).

# Countries observed in 2008 with life expectancy over 80
gm |>
  filter(year == 2008, life_expectancy > 80)
# A tibble: 27 × 33
  country    year smoking_female smoking_male lungcancer_newcases_female
  <chr>     <dbl>          <dbl>        <dbl>                      <dbl>
1 Andorra    2008             NA           NA                       15.2
2 Australia  2008             NA           NA                       25.9
# ℹ 25 more rows
  • Multiple conditions separated by commas are combined with AND (&).

filter() with OR

Use | explicitly for OR:

# Rows from Africa OR Europe
gm |> filter(continent == "Africa" | continent == "Europe")
# A tibble: 26,490 × 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
# ℹ 26,488 more rows
# Equivalent shortcut with %in%: same rows
identical(gm |> filter(continent == "Africa" | continent == "Europe"),
          gm |> filter(continent %in% c("Africa", "Europe")))
[1] TRUE

filter() and Missing Values

filter() silently drops rows where the condition evaluates to NA!

# Rows where sugar consumption exceeds 40 g/day vs. at most 40
gm |> filter(sugar > 40) |> nrow()
[1] 7033
gm |> filter(sugar <= 40) |> nrow()
[1] 2325
gm |> filter(is.na(sugar)) |> nrow()   # rows neither condition kept
[1] 56173
nrow(gm)                               # the three counts add up to this
[1] 65531

Always ask: “How many rows did I lose, and why?” Check with nrow() before and after filtering.

arrange(): Ordering Rows

# Lowest child mortality first
gm |>
  filter(year == 2008) |>
  arrange(child_mortality) |>
  select(country, year, child_mortality)  # (select() is next cycle)
# A tibble: 236 × 3
  country           year child_mortality
  <chr>            <dbl>           <dbl>
1 Iceland           2008            2.72
2 Hong Kong, China  2008            2.82
# ℹ 234 more rows

arrange(): Descending Order

# Highest first: wrap in desc()
gm |>
  filter(year == 2008) |>
  arrange(desc(life_expectancy)) |>
  select(country, year, life_expectancy)
# A tibble: 236 × 3
  country           year life_expectancy
  <chr>            <dbl>           <dbl>
1 Japan             2008            83.3
2 Hong Kong, China  2008            82.7
# ℹ 234 more rows

arrange(): Tie-Breakers

# Sort by continent, then by population within continent
gm |>
  arrange(continent, desc(population)) |>
  select(country, year, continent, population)
# A tibble: 65,531 × 4
  country  year continent population
  <chr>   <dbl> <chr>          <dbl>
1 Nigeria  2099 Africa        733000
2 Nigeria  2098 Africa        728000
# ℹ 65,529 more rows
  • NA values are always placed last, regardless of direction.

👥 Paired Exercise 1: High Smoking Rates (10 min)

Task

In your week-05-inclass.qmd worksheet:

  1. Start from gm and keep only rows for the year 2004 (the most recent year with smoking data).
  2. Keep countries where smoking_male is not missing.
  3. Keep countries where smoking_male exceeds 50 (percent).
  4. Arrange the result from highest to lowest smoking_male.
  5. Report how many countries remain using nrow().

Checklist

  • One single pipeline using |>.
  • filter() conditions can share one call or chain several.
  • Did you remember desc()?

Cycle 2: Selecting & Renaming Columns

select(): Keeping Columns

With 33 columns, most analyses need only a handful:

gm |> select(country, year, life_expectancy)  # id + outcome columns
# A tibble: 65,531 × 3
  country  year life_expectancy
  <chr>   <dbl>           <dbl>
1 Albania  1999            75.4
2 Albania  2000            76  
# ℹ 65,529 more rows
gm |> select(country:year)    # a consecutive range of columns
# A tibble: 65,531 × 2
  country  year
  <chr>   <dbl>
1 Albania  1999
2 Albania  2000
# ℹ 65,529 more rows

select(): Dropping Columns

gm |> select(-population, -HDI)   # drop with a minus sign
# A tibble: 65,531 × 31
  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
# ℹ 65,529 more rows

select() Helper Functions

Match columns by name pattern instead of typing them all:

# All smoking-related columns
gm |> select(country, year, starts_with("smoking"))
# A tibble: 65,531 × 4
  country  year smoking_female smoking_male
  <chr>   <dbl>          <dbl>        <dbl>
1 Albania  1999              4           NA
2 Albania  2000             NA           NA
# ℹ 65,529 more rows
# Any column mentioning cancer
gm |> select(country, year, contains("cancer"))
# A tibble: 65,531 × 6
  country  year lungcancer_newcases_female lungcancer_newcases_male
  <chr>   <dbl>                      <dbl>                    <dbl>
1 Albania  1999                       11.1                     46.1
2 Albania  2000                       10.8                     43.8
# ℹ 65,529 more rows

More select() Helpers

# All columns measured separately for each sex
gm |> select(country, year, ends_with("_male"), ends_with("_female"))
# A tibble: 65,531 × 16
  country  year smoking_male lungcancer_newcases_male alcohol_male
  <chr>   <dbl>        <dbl>                    <dbl>        <dbl>
1 Albania  1999           NA                     46.1         10.6
2 Albania  2000           NA                     43.8         11.5
# ℹ 65,529 more rows
  • starts_with(), ends_with(), contains() are your workhorses.
  • where(is.numeric) selects by column type.

rename(): Clear Column Names

rename(new_name = old_name), and the rest of the data stays untouched:

gm |>
  select(country, year, life_expectancy, GDP_per_capita) |>
  rename(life_exp = life_expectancy,
         gdp = GDP_per_capita)
# A tibble: 65,531 × 4
  country  year life_exp   gdp
  <chr>   <dbl>    <dbl> <dbl>
1 Albania  1999     75.4  1.96
2 Albania  2000     76    2.14
# ℹ 65,529 more rows

Tip

select() can rename while selecting: select(life_exp = life_expectancy). Use rename() when you want to keep all other columns.

👥 Paired Exercise 2: A Tidy Cancer Table (10 min)

Task

  1. From gm, keep rows for 2008 only.
  2. Select country, continent, and every column that contains "lungcancer".
  3. Rename lungcancer_newcases_female to lung_f and lungcancer_newcases_male to lung_m.
  4. Arrange by lung_m in descending order and display the top rows with head().

Checklist

  • One pipeline, four verbs.
  • contains() saves typing long names.
  • Rename after selecting: shorter names to work with!

Cycle 3: Creating New Variables with mutate()

mutate(): New Columns from Old

mutate() adds columns to the end of the data frame; existing columns are preserved.

# Units (see ?gm): GDP_per_capita is in $1,000, population is in 1,000 people,
# so their product is in millions of dollars.
gm |>
  filter(year == 2008) |>
  select(country, population, GDP_per_capita) |>
  mutate(gdp_millions = GDP_per_capita * population)
# A tibble: 236 × 4
  country     population GDP_per_capita gdp_millions
  <chr>            <dbl>          <dbl>        <dbl>
1 Afghanistan      28400          0.492       13973.
2 Angola           22500          3.96        89100 
# ℹ 234 more rows
  • Right side is any vectorized expression (Week 2 arithmetic!).
  • Check the units before you multiply or divide. ?gm documents them.

mutate(): Building on New Columns

New columns can be built from columns you just created:

gm |>
  filter(year == 2008) |>
  select(country, population, GDP_per_capita) |>
  mutate(gdp_millions = GDP_per_capita * population,
         gdp_billions = gdp_millions / 1e3)
# A tibble: 236 × 5
  country     population GDP_per_capita gdp_millions gdp_billions
  <chr>            <dbl>          <dbl>        <dbl>        <dbl>
1 Afghanistan      28400          0.492       13973.         14.0
2 Angola           22500          3.96        89100          89.1
# ℹ 234 more rows

mutate() with Logical Columns

A comparison creates a TRUE/FALSE column, ready for later filtering:

gm |>
  filter(year == 2008) |>
  select(country, life_expectancy) |>
  mutate(above_80 = life_expectancy > 80)
# A tibble: 236 × 3
  country     life_expectancy above_80
  <chr>                 <dbl> <lgl>   
1 Afghanistan            59.9 FALSE   
2 Angola                 59.5 FALSE   
# ℹ 234 more rows

mutate() for Unit Conversions

# Unit conversions are classic mutate() one-liners
# population is recorded in thousands of people (?gm)
gm |>
  filter(year == 2008) |>
  select(country, population) |>
  mutate(pop_millions = population / 1e3)
# A tibble: 236 × 3
  country     population pop_millions
  <chr>            <dbl>        <dbl>
1 Afghanistan      28400         28.4
2 Angola           22500         22.5
# ℹ 234 more rows

Warning

mutate() never changes the original gm object. To keep your work, assign the result: gm2008_clean <- gm |> ...

Putting It All Together

smoking_2004 <- gm |>
  filter(year == 2004, !is.na(smoking_male), !is.na(smoking_female)) |>
  select(country, continent, population,
         starts_with("smoking")) |>
  rename(male = smoking_male, female = smoking_female) |>
  mutate(gap = male - female,
         pop_millions = population / 1e3) |>   # population is in thousands
  arrange(desc(gap))

head(smoking_2004)
# A tibble: 6 × 7
  country   continent population female  male   gap pop_millions
  <chr>     <chr>          <dbl>  <dbl> <dbl> <dbl>        <dbl>
1 Indonesia Asia          226000    4.5  65.9  61.4          226
2 China     Asia         1330000    3.7  59.5  55.8         1330
# ℹ 4 more rows

Every verb answers one question. The pipeline tells the whole story.

👥 Paired Exercise 3: Food & Longevity (10 min)

Task

  1. From gm, keep 2008 rows with non-missing food_supply and life_expectancy.
  2. Select country, continent, food_supply, life_expectancy.
  3. Create food_kcal_deficit: 2500 - food_supply (positive = below the 2,500 kcal benchmark).
  4. Create long_lived: TRUE when life_expectancy is at least 75.
  5. Arrange by food_kcal_deficit (largest deficit first) and inspect the top 10.

Checklist

  • Two new columns in one mutate() call.
  • arrange(desc(...)) for the sort.
  • head(..., 10) at the end of the pipe.

Cycle 4: Pipelines in Practice + Quiz

Debugging Pipelines: Read Them Like Steps

Run a pipeline one verb at a time to find where things go wrong:

gm |>
  filter(year == 2008)            # Step 1: run up to here. Rows look right?
# A tibble: 236 × 33
  country      year smoking_female smoking_male lungcancer_newcases_female
  <chr>       <dbl>          <dbl>        <dbl>                      <dbl>
1 Afghanistan  2008             NA           NA                       4.2 
2 Angola       2008             NA           NA                       5.05
# ℹ 234 more rows

Debugging Pipelines: Add One Verb at a Time

gm |>
  filter(year == 2008) |>
  select(country, sugar)          # Step 2: expected columns present?
# A tibble: 236 × 2
  country     sugar
  <chr>       <dbl>
1 Afghanistan  23.3
2 Angola       40.2
# ℹ 234 more rows
  • Highlight everything up to (but not including) a pipe and press Cmd/Ctrl + Enter.
  • nrow(), names(), and head() are your cheap diagnostic probes.

Common dplyr Pitfalls

1. = vs == inside filter()

gm |> filter(year = 2008)
Error in `filter()`:
! We detected a named input.
ℹ This usually means that you've used `=` instead of `==`.
ℹ Did you mean `year == 2008`?

Fix: filter(year == 2008).

2. Forgetting to assign

gm |> mutate(x = sugar * 7)
# printed... and discarded!

3. Quoting column names

# Both work; the bare name is idiomatic
identical(gm |> select("country"),
          gm |> select(country))
[1] TRUE

4. Overwriting your raw data

gm <- gm |> filter(year == 2008)
# original gm is gone for this session!
# Use a new name: gm_2008

AI Corner: Auditing an AI-Written Pipeline

An AI assistant produced this code for “average sugar consumption in Asia in 2008”:

gm %>%
  group_by(continent) %>%
  summarize(mean_sugar = mean(sugar))
# A tibble: 6 × 2
  continent mean_sugar
  <chr>          <dbl>
1 Africa            NA
2 Americas          NA
# ℹ 4 more rows

Three audit findings:

  1. It used verbs (group_by, summarize) we can’t verify yet, when a simple filter() + mean() answers the question.
  2. It never filtered year == 2008, so it silently averages all years.
  3. mean(sugar) returns NA because missing values were never handled.

AI Corner: The Verified Version

# A verifiable Week-5 answer:
asia_sugar <- gm |> filter(year == 2008, continent == "Asia", !is.na(sugar))
mean(asia_sugar$sugar)
[1] 71.68293

Important

Zone 2 rule: you may only submit AI-assisted code that you can explain and verify line by line.

📝 Quiz 2 (Last 30 Minutes)

  • Coverage: Weeks 3–4 (data structures, import, ggplot2).
  • Format: Paper-based, closed-book, no electronic devices.
  • Length: 20 minutes, multiple choice.

Note

Laptops closed, please. Your in-class worksheet should already be pushed to GitHub before the quiz begins.

Wrap-Up & Next Steps

Before We Meet Again

📌 To Do This Week

  • Homework 5 (dplyr wrangling): due date on the course website.
  • Read: R02Pro Ch 8.5–8.8 & Ch 9 (grouped summaries, joins, tidy data).
  • Push today’s in-class worksheet to GitHub.

🔭 Next Week

  • group_by() + summarize(): one row per group.
  • Combining tables with joins (left_join()).
  • Reshaping data with tidyr (pivot_longer, pivot_wider).

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