library(r02pro)
library(dplyr)
dim(gm) # rows, columns[1] 65531 33
GPH-GU 2182: Statistical Programming in R · Fall 2026
New York University · School of Global Public Health
2026-09-30
|>): Readable multi-step pipelines.filter() and arrange().select() and rename().mutate() for new columns.dplyr wrangling).Analysts spend 50–80% of their time preparing data, not modeling it.
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? |
gm)The gm dataset from the r02pro package tracks health indicators for world countries over time.
country, continent, year, populationlife_expectancy, child_mortality, sugar, food_supplysmoking_male, smoking_female, GDP_per_capita, HDIOne row = one country in one year.
|>The pipe takes the object on its left and passes it as the first argument to the function on its right.
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 Matchfilter() keeps rows where a logical condition is TRUE (the same logicals you built in Week 2!).
# 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
&).filter() with ORUse | explicitly for OR:
# 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
[1] TRUE
filter() and Missing Valuesfilter() silently drops rows where the condition evaluates to NA!
[1] 7033
[1] 2325
[1] 56173
[1] 65531
Always ask: “How many rows did I lose, and why?” Check with nrow() before and after filtering.
arrange(): Ordering Rowsarrange(): Descending Orderarrange(): Tie-Breakers# 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.In your week-05-inclass.qmd worksheet:
gm and keep only rows for the year 2004 (the most recent year with smoking data).smoking_male is not missing.smoking_male exceeds 50 (percent).smoking_male.nrow().|>.filter() conditions can share one call or chain several.desc()?select(): Keeping ColumnsWith 33 columns, most analyses need only a handful:
# 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
# A tibble: 65,531 × 2
country year
<chr> <dbl>
1 Albania 1999
2 Albania 2000
# ℹ 65,529 more rows
select(): Dropping Columnsselect() Helper FunctionsMatch columns by name pattern instead of typing them all:
# 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
# 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
select() Helpers# 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 Namesrename(new_name = old_name), and the rest of the data stays untouched:
# 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.
gm, keep rows for 2008 only.country, continent, and every column that contains "lungcancer".lungcancer_newcases_female to lung_f and lungcancer_newcases_male to lung_m.lung_m in descending order and display the top rows with head().contains() saves typing long names.mutate()mutate(): New Columns from Oldmutate() adds columns to the end of the data frame; existing columns are preserved.
# 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
?gm documents them.mutate(): Building on New ColumnsNew columns can be built from columns you just created:
# 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 ColumnsA comparison creates a TRUE/FALSE column, ready for later filtering:
mutate() for Unit Conversions# 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 |> ...
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.
gm, keep 2008 rows with non-missing food_supply and life_expectancy.country, continent, food_supply, life_expectancy.food_kcal_deficit: 2500 - food_supply (positive = below the 2,500 kcal benchmark).long_lived: TRUE when life_expectancy is at least 75.food_kcal_deficit (largest deficit first) and inspect the top 10.mutate() call.arrange(desc(...)) for the sort.head(..., 10) at the end of the pipe.Run a pipeline one verb at a time to find where things go wrong:
# A tibble: 236 × 2
country sugar
<chr> <dbl>
1 Afghanistan 23.3
2 Angola 40.2
# ℹ 234 more rows
nrow(), names(), and head() are your cheap diagnostic probes.dplyr Pitfalls= vs == inside filter()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).
An AI assistant produced this code for “average sugar consumption in Asia in 2008”:
# A tibble: 6 × 2
continent mean_sugar
<chr> <dbl>
1 Africa NA
2 Americas NA
# ℹ 4 more rows
Three audit findings:
group_by, summarize) we can’t verify yet, when a simple filter() + mean() answers the question.year == 2008, so it silently averages all years.mean(sugar) returns NA because missing values were never handled.[1] 71.68293
Important
Zone 2 rule: you may only submit AI-assisted code that you can explain and verify line by line.
ggplot2).Note
Laptops closed, please. Your in-class worksheet should already be pushed to GitHub before the quiz begins.
group_by() + summarize(): one row per group.left_join()).tidyr (pivot_longer, pivot_wider).Questions? Office hours are listed on the syllabus page, or email anytime.