Mastering dplyr for Data Wrangling
Todayβs Mission: Data Wrangling
Transform messy data into insights!
Tidyverse: Rβs Modern Data Science Toolkit
A collection of packages designed to work together seamlessly!
# Install once
install.packages("tidyverse")
# Load in every session
library(tidyverse)
# You get a buncha packages!
# β
dplyr β Data manipulation
# β
ggplot2 β Visualization
# β
tidyr β Data tidying
# β
readr β Reading data
# β
purrr β Functional programming
# β
tibble β Modern data frames
# β
stringr β String manipulation
# β
forcats β Factor handling
%>% and |>Make Your Code Read Like a Story!
The pipe %>% (and also written as |>) passes output from one function to the next.
Without Pipes
Keyboard shortcut: Cmd/Ctrl + Shift + M = %>%
Tip
You are not the only person reading your code. Write it readably for humans, not just computers!
Imagine looking for a single book in a messy bookstore. Do you search by genre, author, or title? How to separate the book from the others?


Note
Data manipulation is a similar challenge: finding the right information in a messy dataset.
Six powerful functions that solve 90% of data manipulation tasks!
| Verb | Purpose | Example |
|---|---|---|
select() |
Choose columns | select(data, name, age) |
filter() |
Choose rows | filter(data, age > 18) |
mutate() |
Create/modify columns | mutate(data, age_squared = age^2) |
Six powerful functions that solve 90% of data manipulation tasks!
| Verb | Purpose | Example |
|---|---|---|
arrange() |
Sort rows | arrange(data, desc(age)) |
summarize() |
Aggregate data | summarize(data, mean_age = mean(age)) |
group_by() |
Group for operations | group_by(data, category) |
Pick the columns you need
# Load example data
library(tidyverse)
data(mtcars)
# Select specific columns
mtcars %>% select(mpg, cyl, hp)
# Select range of columns
mtcars %>% select(mpg:hp)
# Select by pattern
mtcars %>% select(starts_with("m")) # mpg
mtcars %>% select(ends_with("p")) # hp, disp
mtcars %>% select(contains("ar")) # gear, carb
# Exclude columns
mtcars %>% select(-wt, -qsec)
# Reorder columns
mtcars %>% select(hp, mpg, everything())
# Rename while selecting
mtcars %>% select(miles_per_gallon = mpg, horsepower = hp)Keep only rows that meet conditions
# Simple filter
mtcars %>% filter(mpg > 20)
# Multiple conditions (AND)
mtcars %>% filter(mpg > 20, cyl == 4)
mtcars %>% filter(mpg > 20 & cyl == 4)
# OR conditions
mtcars %>% filter(cyl == 4 | cyl == 6)
mtcars %>% filter(cyl %in% c(4, 6))
# Complex conditions
mtcars %>% filter(
mpg > 20,
cyl %in% c(4, 6),
hp < 100
)
# Pattern matching
library(datasets)
data(iris)
iris %>% filter(grepl("setosa", Species))
# Missing values
data %>% filter(is.na(column)) # Keep NAs
data %>% filter(!is.na(column)) # Remove NAsAdd or change variables
# Create new column
mtcars %>%
mutate(hp_per_cyl = hp / cyl)
# Multiple new columns
mtcars %>%
mutate(
kml = mpg * 0.425, # Convert to km/L
hp_per_cyl = hp / cyl,
is_powerful = hp > 150
)
# Use newly created columns
mtcars %>%
mutate(
hp_per_cyl = hp / cyl,
rating = ifelse(hp_per_cyl > 50, "High", "Low")
)
# Modify existing column
mtcars %>%
mutate(mpg = round(mpg, 0))
# Conditional mutation
mtcars %>%
mutate(
efficiency = case_when(
mpg > 25 ~ "High",
mpg > 20 ~ "Medium",
TRUE ~ "Low"
)
)Order your data
# Sort ascending (default)
mtcars %>% arrange(mpg)
# Sort descending
mtcars %>% arrange(desc(mpg))
# Multiple columns
mtcars %>% arrange(cyl, desc(mpg))
# Useful with other verbs
mtcars %>%
filter(hp > 100) %>%
select(mpg, hp, cyl) %>%
arrange(desc(mpg))
# Top N
mtcars %>%
arrange(desc(mpg)) %>%
head(5) # Top 5 most efficient
# Bottom N
mtcars %>%
arrange(mpg) %>%
head(5) # 5 least efficientCalculate summary statistics
# Single summary
mtcars %>%
summarize(mean_mpg = mean(mpg))
# Multiple summaries
mtcars %>%
summarize(
avg_mpg = mean(mpg),
sd_mpg = sd(mpg),
min_mpg = min(mpg),
max_mpg = max(mpg),
count = n()
)
# Useful functions in summarize()
data %>%
summarize(
mean = mean(x),
median = median(x),
sd = sd(x),
min = min(x),
max = max(x),
sum = sum(x),
n = n(), # Count rows
n_distinct = n_distinct(x) # Count unique values
)The Game Changer!
group_by() + summarize() = Super powerful analysis
# Group by cylinder and summarize
mtcars %>%
group_by(cyl) %>%
summarize(
count = n(),
avg_mpg = mean(mpg),
avg_hp = mean(hp)
)
# cyl count avg_mpg avg_hp
# 4 11 26.7 82.6
# 6 7 19.7 122.3
# 8 14 15.1 209.2
# Multiple grouping variables
mtcars %>%
group_by(cyl, gear) %>%
summarize(avg_mpg = mean(mpg))
# Group + mutate (add group stats to each row)
mtcars %>%
group_by(cyl) %>%
mutate(
mean_mpg_by_cyl = mean(mpg),
diff_from_mean = mpg - mean_mpg_by_cyl
)Note
Work with a partner first. Write each pipeline before checking the following solution slides.
Using mtcars, create a table with only mpg, hp, and wt for cars with more than 150 horsepower using commands, use select() and filter(). Use arrange() with argument desc(wt) to put the heaviest cars first.
Using mtcars, add a column named power_per_weight equal to horsepower divided by weight. Keep only cars with power_per_weight greater than 50, then show mpg, hp, wt, and the new column.
Using iris, calculate the number of flowers and the average petal length for each species. Sort the result from the largest average petal length to the smallest.