R dplyr
last modified November 19, 2026
dplyr is a package for manipulating tables with a small set of verbs. Each
verb does one thing: filter keeps rows, select keeps
columns, mutate adds columns, arrange sorts rows,
and summarise reduces a table to a few numbers. The verbs take a
data frame first and return a data frame, so they can be chained with the pipe
into a readable sequence of steps. This article covers those five verbs,
grouped summaries, and the joins that combine two tables by a key. The
examples use dplyr 1.2.1 with R 4.5.2.
The examples need the dplyr package, which is not part of base R. Install it
once with install.packages("dplyr"); the
installing packages section of the
introduction explains the details.
Filtering rows
filter keeps the rows for which a condition is true. The
condition is evaluated inside the table, so column names are written without
a prefix and no quotation marks are needed. The native pipe |>
passes the result of the left side as the first argument of the right side.
Older code often uses the magrittr pipe %>%, which behaves the
same way for these examples.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger"),
score = c(90, 85, 66, 78),
subject = c("math", "art", "math", "art")
)
print(filter(students, score >= 80))
print(students |> filter(subject == "math"))
The first call keeps Ada and Grace, whose scores reach 80. The second keeps
the two mathematics students, one of whom failed, because the condition is
about the subject and not about the score. The package is loaded with
suppressPackageStartupMessages so that its startup banner does
not appear in the output; the function is otherwise an ordinary
library call.
$ Rscript filtering-rows.R # A tibble: 2 × 3 name score subject <chr> <dbl> <chr> 1 Ada 90 math 2 Grace 85 art # A tibble: 2 × 3 name score subject <chr> <dbl> <chr> 1 Ada 90 math 2 Alan 66 math
Selecting and renaming columns
select keeps the named columns in the order given, and a minus
sign removes a column instead. rename changes a name while
keeping every column and every value. Both functions accept bare column names
because they use the same non-standard evaluation as filter.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan"),
score = c(90, 85, 66),
hours = c(12, 10, 8)
)
print(select(students, name, score))
print(select(students, -hours))
print(rename(students, points = score))
The first result has two columns, the second drops hours, and
the third keeps all three columns with score renamed to
points. Helper functions such as starts_with,
ends_with, and where can replace the explicit names
when a table has many columns. The selection is not modified in place; every
verb returns a new tibble.
$ Rscript selecting-columns.R # A tibble: 3 × 2 name score <chr> <dbl> 1 Ada 90 2 Grace 85 3 Alan 66 # A tibble: 3 × 2 name score <chr> <dbl> 1 Ada 90 2 Grace 85 3 Alan 66 # A tibble: 3 × 3 name points hours <chr> <dbl> <dbl> 1 Ada 90 12 2 Grace 85 10 3 Alan 66 8
Creating columns
mutate adds a column or replaces an existing one. The expression
sees all the columns of the table and is evaluated once for the whole column,
which is why a comparison such as score >= 70 produces one
logical value per row. case_when chooses among several conditions
and is the readable replacement for a chain of nested ifelse
calls.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger"),
score = c(90, 85, 66, 78)
)
print(mutate(students, passed = score >= 70))
print(mutate(students, grade = case_when(
score >= 90 ~ "A",
score >= 80 ~ "B",
score >= 70 ~ "C",
TRUE ~ "F"
)))
The first call adds a logical passed column. The second maps each
score to a letter grade: 90 and above become A, 80 and above B, 70 and above
C, and everything else F. The final condition TRUE ~ "F" is a
catch-all, which case_when requires because it has no default
branch of its own.
$ Rscript new-columns.R # A tibble: 4 × 3 name score passed <chr> <dbl> <lgl> 1 Ada 90 TRUE 2 Grace 85 TRUE 3 Alan 66 FALSE 4 Edsger 78 TRUE # A tibble: 4 × 3 name score grade <chr> <dbl> <chr> 1 Ada 90 A 2 Grace 85 B 3 Alan 66 F 4 Edsger 78 C
Sorting rows
arrange sorts a table by one or more columns. The function
desc reverses the order for a single key, and additional keys
break ties in the order they are listed. Row names are irrelevant, because a
tibble does not have any.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger"),
score = c(90, 85, 66, 78),
subject = c("math", "art", "math", "art")
)
print(arrange(students, desc(score)))
print(arrange(students, subject, desc(score)))
The first result runs from the highest score to the lowest. The second groups
the subjects alphabetically and sorts by score inside each subject, so Grace
comes before Edsger in art and Ada before Alan in mathematics. Sorting is a
separate verb rather than an argument of filter, which keeps each
step small and composable.
$ Rscript sorting-rows.R # A tibble: 4 × 3 name score subject <chr> <dbl> <chr> 1 Ada 90 math 2 Grace 85 art 3 Edsger 78 art 4 Alan 66 math # A tibble: 4 × 3 name score subject <chr> <dbl> <chr> 1 Grace 85 art 2 Edsger 78 art 3 Ada 90 math 4 Alan 66 math
Summarising a table
summarise evaluates one or more expressions and returns a
one-row tibble with one column per expression. The function n()
counts the rows of the current group, and ordinary summary functions such as
mean and sd work on the columns.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger"),
score = c(90, 85, 66, 78)
)
print(summarise(students,
n = n(),
mean_score = mean(score),
sd_score = sd(score)
))
The result has one row and three columns: the count, the mean score, and the standard deviation. The column names come from the argument names, so the output is self-describing. Without a grouping, the whole table is one group; the next section splits it into several.
$ Rscript summarising.R
# A tibble: 1 × 3
n mean_score sd_score
<int> <dbl> <dbl>
1 4 79.8 10.4
Grouped summaries
group_by marks a column as a grouping key. A following
summarise computes one row per group instead of one row for the
whole table, and the grouping is removed from the result. count
is the shortcut for counting rows per group.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger", "Barbara", "Donald"),
score = c(90, 85, 66, 78, 95, 71),
subject = c("math", "art", "math", "art", "math", "art")
)
print(students |> group_by(subject) |> summarise(avg = mean(score), n = n()))
print(count(students, subject))
Art and mathematics both contain three students, with averages of 78 and
83.67. The groups appear in alphabetical order of the key, not in the order
in which the rows first occur. count(students, subject) returns
the same numbers as the grouped summary with n(), without the
mean column.
$ Rscript group.R # A tibble: 2 × 3 subject avg n <chr> <dbl> <int> 1 art 78 3 2 math 83.7 3 # A tibble: 2 × 2 subject n <chr> <int> 1 art 3 2 math 3
Joining tables
A join combines two tables by a shared key. left_join keeps every
row of the first table and fills unmatched columns with NA.
inner_join keeps only keys present on both sides, and
anti_join keeps the rows of the first table whose key is missing
from the second.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(id = c(1, 2, 3), name = c("Ada", "Grace", "Alan"))
scores <- tibble(id = c(1, 2, 4), score = c(90, 85, 70))
print(left_join(students, scores, by = "id"))
print(inner_join(students, scores, by = "id"))
print(anti_join(students, scores, by = "id"))
The left join keeps Alan with a missing score, and the inner join drops him.
The anti join returns Alan alone, because his id 3 has no matching score.
Keys can be named explicitly with by = "id" or matched by
different names with by = c("student_id" = "id").
$ Rscript join.R
# A tibble: 3 × 3
id name score
<dbl> <chr> <dbl>
1 1 Ada 90
2 2 Grace 85
3 3 Alan NA
# A tibble: 2 × 3
id name score
<dbl> <chr> <dbl>
1 1 Ada 90
2 2 Grace 85
# A tibble: 1 × 2
id name
<dbl> <chr>
1 3 Alan
A complete example
The next script builds a small report from six students. It filters the failing score, computes points per hour, sorts by score, and keeps three columns. Each verb is a line in the pipeline, and the whole sequence reads from the input table to the final result.
suppressPackageStartupMessages(library(dplyr))
students <- tibble(
name = c("Ada", "Grace", "Alan", "Edsger", "Barbara", "Donald"),
score = c(90, 85, 66, 78, 95, 71),
hours = c(12, 10, 8, 11, 14, 9)
)
report <- students |>
filter(score >= 70) |>
mutate(points_per_hour = round(score / hours, 2)) |>
arrange(desc(score)) |>
select(name, score, points_per_hour)
print(report)
Barbara leads with 95 points, and Donald closes the list with 71 after Alan
is removed for scoring 66. The ratio column divides two numeric columns that
stay aligned because both belong to the same table. Reordering the pipeline
would change the result: filtering before mutate would keep only
the passing rows from the start, and sorting after select would
work on the reduced table.
$ Rscript report.R # A tibble: 5 × 3 name score points_per_hour <chr> <dbl> <dbl> 1 Barbara 95 6.79 2 Ada 90 7.5 3 Grace 85 8.5 4 Edsger 78 7.09 5 Donald 71 7.89
Next steps
The tibbles article explains the table type that dplyr accepts and returns. The subsetting and apply family articles show the base R operations that the verbs replace, and the data.table article presents a faster alternative with a different syntax. The tidyr article reshapes the tables that these verbs summarise.
Source
dplyr reference: create and modify columns
dplyr reference: group and summarise
In this article we have filtered rows with filter, selected and
renamed columns with select and rename, and created
columns with mutate and case_when. We sorted with
arrange, summarised with summarise and
n(), and grouped with group_by and
count. We joined two tables with left_join,
inner_join, and anti_join, and combined the verbs
into one pipeline. The series continues with
R tidyr.
Author
List all R Language tutorials.