dplyr Tutorial: Learn Data Manipulation in R
dplyr turns data wrangling in R into a few readable verbs. This free tutorial takes you from installing the package to joins and window functions in 14 short lessons, all built on one dataset.
What is dplyr?
dplyr is an R package for transforming data frames. Each task you do again and again, such as keeping some rows, picking some columns or calculating a group average, has its own function named after the action. Chain those functions together and a data analysis reads almost like a sentence.
Here is the idea. Data flows from left to right through a series of steps:
- starwars
- filter()
- group_by()
- summarise()
- arrange()
The |> symbol between the steps is the pipe. It passes the result of one step into the next. You will meet it properly in the pipe operator lesson.
dplyr is part of the tidyverse, a family of R packages that share one design. Learning it once also makes tidyr, ggplot2 and readr easier to pick up.
Install and load dplyr
Install the package once, then load it at the start of every R session.
# install once
install.packages("dplyr")
# load in every new session
library(dplyr)
# check which version you have
packageVersion("dplyr")
If you plan to use the rest of the tidyverse as well, install.packages("tidyverse") installs dplyr along with ggplot2, tidyr and others. Then library(tidyverse) loads them together.
When you load dplyr, R prints a message that filter() and lag() from the stats package are masked. This is normal. After loading, filter() means the dplyr version. Use stats::filter() if you ever need the original.
The sample data used in this tutorial
Every lesson uses starwars, a data frame that ships with dplyr. It lists characters from the films with their height, mass, species, home planet and more. Because it is built in, you can run every example without importing a file.
library(dplyr)
glimpse(starwars)
glimpse() shows every column and its type in a compact view. You will see columns such as name, height, mass, species and homeworld. Some values are NA (missing), which makes the data a realistic place to practise.
Your first dplyr pipeline
This example finds the average height of humans for each home planet, and lists the tallest groups first.
starwars |>
filter(species == "Human", !is.na(height)) |>
group_by(homeworld) |>
summarise(
characters = n(),
avg_height = mean(height),
.groups = "drop"
) |>
filter(characters > 1) |>
arrange(desc(avg_height))
Read it one line at a time:
filter()keeps only humans whose height is known.group_by()splits the rows by home planet.summarise()collapses each group into one row with a count and an average.- The second
filter()keeps planets with more than one character. arrange(desc(avg_height))sorts from tallest average to shortest.
Nothing here changes starwars itself. dplyr returns a new data frame, so assign it with <- if you want to keep the result.
The dplyr verbs at a glance
Most of what you do with dplyr uses the functions below. Each one has its own lesson.
| Function | What it does | Lesson |
|---|---|---|
select() | Keep, drop or reorder columns | dplyr select |
filter() | Keep rows that meet a condition | dplyr filter |
mutate() | Create or change columns | dplyr mutate |
arrange() | Sort rows | dplyr arrange |
rename() | Change column names | dplyr rename |
group_by() + summarise() | Calculate summaries per group | dplyr group_by |
count(), distinct() | Count values, remove duplicates | dplyr count |
left_join() and friends | Combine two tables | dplyr joins |
All dplyr lessons
The lessons build on each other. If you are new to dplyr, go in order. If you are looking for one function, jump straight to its lesson.
Foundations
- Pipe operatorChain steps with %>% and |>, and know when to use each.
- select()Pick, drop and reorder columns, including helpers like starts_with().
- filter()Keep rows with conditions, %in%, between() and missing values.
- mutate()Add new columns and change existing ones.
- arrange()Sort a data frame by one or more columns.
- rename()Rename one column, many columns, or all at once.
Summarising data
- group_by() + summarise()Calculate means, sums and counts for each group.
- count(), distinct()Count categories and find or remove duplicates.
Going further
- case_when()Create columns from several if-else conditions.
- across()Apply one function to many columns in a single step.
- JoinsCombine tables with left_join(), inner_join(), anti_join() and more.
- slice()Take rows by position, top and bottom values, or a random sample.
- Window functionsUse lag(), lead(), rank() and running totals within groups.
Reference
New to R? Start with the R basics lessons first, especially vectors and data frames, then come back here.
dplyr vs base R
Everything dplyr does can also be done in base R. The difference is mostly readability. Compare these tasks on the built-in mtcars data:
| Task | Base R | dplyr |
|---|---|---|
| Pick columns | mtcars[, c("mpg", "cyl")] | select(mtcars, mpg, cyl) |
| Filter rows | mtcars[mtcars$mpg > 25, ] | filter(mtcars, mpg > 25) |
| New column | mtcars$kpl <- mtcars$mpg * 0.425 | mutate(mtcars, kpl = mpg * 0.425) |
| Sort | mtcars[order(-mtcars$mpg), ] | arrange(mtcars, desc(mpg)) |
| Group average | aggregate(mpg ~ cyl, mtcars, mean) | mtcars |> group_by(cyl) |> summarise(avg = mean(mpg)) |
In dplyr you write column names without quotes or the mtcars$ prefix, and the steps read in the order you think them. You do not have to pick one for life. Many R users mix both, and the lessons here point out where base R is still handy.
Common beginner problems
- "could not find function": you forgot
library(dplyr)in this session. - Result disappears: dplyr does not change your data. Save it with
clean <- starwars |> .... - Averages return NA: the column has missing values. Use
mean(x, na.rm = TRUE)or filter them out first. - Strange results after grouping: the data is still grouped. Finish with
ungroup()or.groups = "drop". - Wrong
filter()runs: another package masked it. Writedplyr::filter()to be explicit.
dplyr FAQ
What is dplyr used for?
dplyr is an R package for manipulating data frames. You use it to select columns, filter rows, create new variables, sort, summarise by group and join tables.
Is dplyr part of the tidyverse?
Yes. dplyr is one of the core tidyverse packages. You can load it alone with library(dplyr) or together with the others using library(tidyverse).
Do I need to know base R before learning dplyr?
You should be comfortable with vectors and data frames first. You do not need to master base R subsetting, because dplyr verbs replace most of it.
Should I use %>% or |> with dplyr?
Both work. The native pipe |> comes with R 4.1 and later and needs no package. The %>% pipe from magrittr is loaded with dplyr and has a few extra features.
Is dplyr faster than base R?
For most everyday tasks the speed is similar. dplyr is chosen mainly for readability. For very large data, packages such as data.table or dtplyr can be faster.
Ready to start? Begin with the pipe operator lesson, the foundation of every other dplyr lesson.