dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

dplyr Cheat Sheet for R: Topic-by-Topic Reference

Updated

A practical, topic-wise dplyr cheat sheet for R. Find the exact function you need under a clear heading, check its purpose, and copy a concise example for everyday data cleaning, transformation, and analysis.

1. Setup and pipe syntax

Use this dplyr cheat sheet for R as a quick lookup guide. Each section contains only the functions relevant to that task, so you can jump straight to the operation you need.

# Install once, if needed
install.packages("dplyr")

# Load in each R session
library(dplyr)

# Example data
sales <- tibble(
  product = c("Tea", "Coffee", "Tea", "Juice"),
  region = c("North", "South", "South", "North"),
  units = c(10, 7, 14, 5),
  revenue = c(100, 140, 140, 75)
)
SyntaxMeaningExample
|>Pass the result on the left to the next operationsales |> filter(units > 8)
%>%Pipe from the magrittr package, commonly used in older dplyr codesales %>% filter(units > 8)
group_by()Define groups for later calculationsgroup_by(region)
ungroup()Remove grouping from a grouped data frameungroup()

Tip: examples below use the base R pipe |>, available in R 4.1 and later. If your project uses %>%, the same dplyr verbs can generally be used with that pipe too.

2. Select columns with select()

Use select() when you want to choose, exclude, or reorder variables. It changes which columns are returned, not which observations are kept.

TaskSyntaxWhat it does
Keep named columnsselect(product, revenue)Keep only product and revenue
Keep a rangeselect(product:units)Keep columns from product through units in their current order
Exclude a columnselect(-region)Keep every column except region
Select by prefixselect(starts_with("rev"))Keep columns whose names start with rev
Select by suffixselect(ends_with("id"))Keep columns whose names end with id
Select by name patternselect(contains("sale"))Keep columns whose names contain sale
Select numeric columnsselect(where(is.numeric))Keep columns that satisfy is.numeric
Rename while selectingselect(total = revenue)Keep revenue and name it total
sales |>
  select(product, region, revenue)

sales |>
  select(-units)

sales |>
  select(where(is.numeric))

For a deeper explanation of column selection, see the dplyr select() tutorial.

3. Filter rows with filter()

Use filter() to keep observations that meet one or more conditions. Character values should be quoted; column names normally should not.

TaskSyntaxMeaning
Greater thanfilter(revenue > 100)Keep revenue above 100
Equal to textfilter(region == "North")Keep rows in North
Two conditions (AND)filter(units > 5, revenue > 100)Both conditions must be true
Either condition (OR)filter(region == "North" | region == "South")Keep rows matching either condition
Value in a listfilter(product %in% c("Tea", "Juice"))Keep Tea or Juice
Exclude a valuefilter(product != "Tea")Remove Tea rows
Between limitsfilter(between(revenue, 75, 140))Keep values from 75 through 140, inclusive
Missing valuesfilter(is.na(revenue))Keep rows with missing revenue
Non-missing valuesfilter(!is.na(revenue))Keep rows with a known revenue value
sales |>
  filter(region == "North", revenue >= 75)

sales |>
  filter(product %in% c("Tea", "Juice"))

Remember: & means AND, | means OR, and ! means NOT. See the filter() in R guide for more examples.

4. Create and change columns with mutate()

mutate() adds new columns or replaces existing ones. Use it for calculated variables, ratios, flags, transformations, and other row-level operations.

TaskSyntaxResult
Add a calculated columnmutate(profit = revenue - cost)Creates profit
Calculate a ratiomutate(revenue_per_unit = revenue / units)Revenue divided by units
Change unitsmutate(revenue_k = revenue / 1000)Revenue expressed in thousands
Replace an existing columnmutate(revenue = revenue * 1.05)Overwrites revenue with adjusted values
Use an earlier new columnmutate(total = units * 10, tax = total * 0.1)tax uses total calculated in the same mutate()
Create a logical flagmutate(high_sales = revenue > 100)TRUE or FALSE for each row
sales |>
  mutate(
    revenue_per_unit = revenue / units,
    high_revenue = revenue > 100
  )

Use case_when() inside mutate() when a new column needs multiple conditions.

5. Sort rows with arrange()

arrange() changes row order. It does not remove observations or columns.

TaskSyntax
Ascending orderarrange(revenue)
Descending orderarrange(desc(revenue))
Sort by multiple columnsarrange(region, desc(revenue))
Put missing values last explicitlyarrange(is.na(revenue), revenue)
Sort within groups for a later calculationarrange(region, desc(revenue))
sales |>
  arrange(desc(revenue))

See the arrange() tutorial. When using lag(), lead(), or cumulative functions, sort the rows into the intended order first.

6. Rename columns with rename()

In rename(), write the new name on the left and the existing name on the right.

sales |>
  rename(sales_region = region, sales_revenue = revenue)
TaskSyntax
Rename one columnrename(sales_total = revenue)
Rename multiple columnsrename(item = product, area = region)
Rename while choosing columnsselect(item = product, sales_total = revenue)

More examples are available in the rename() in R tutorial.

7. Group and summarise with group_by() and summarise()

Use group_by() to define categories and summarise() to calculate a result for each group. This is a standard pattern for reports, dashboards, and exploratory data analysis.

TaskSyntax
Total by regiongroup_by(region) |> summarise(total = sum(revenue))
Average by productgroup_by(product) |> summarise(avg = mean(revenue))
Count rows per groupgroup_by(region) |> summarise(n = n())
Multiple statisticssummarise(total = sum(revenue), average = mean(revenue))
Ignore missing values in sumsummarise(total = sum(revenue, na.rm = TRUE))
Return an ungrouped resultsummarise(total = sum(revenue), .groups = "drop")
sales |>
  group_by(region) |>
  summarise(
    total_revenue = sum(revenue),
    average_revenue = mean(revenue),
    rows = n(),
    .groups = "drop"
  )

n() counts rows in the current group. For a count of non-missing values in a specific column, use sum(!is.na(column)) or an appropriate summary function. Explore group_by() and summarise() examples.

8. Count rows and find distinct values

Use count() for frequency tables and distinct() to identify unique values or rows.

TaskSyntax
Count rows by categorycount(region)
Count combinationscount(region, product)
Sort counts descendingcount(product, sort = TRUE)
Count unique valuesn_distinct(product)
Count unique non-missing valuesn_distinct(product, na.rm = TRUE)
Keep unique productsdistinct(product)
Keep unique combinationsdistinct(region, product)
Keep one row per key and retain other columnsdistinct(product, .keep_all = TRUE)
sales |> count(product, sort = TRUE)

sales |> summarise(unique_products = n_distinct(product))

sales |> distinct(region, product)

Read the count() and distinct() guide for detailed examples and common pitfalls.

9. Conditional values with case_when()

case_when() is useful for assigning labels or categories based on multiple conditions. Put more specific conditions before broader ones and use TRUE ~ as the final fallback when appropriate.

sales |>
  mutate(
    sales_level = case_when(
      revenue >= 130 ~ "High",
      revenue >= 100 ~ "Medium",
      TRUE ~ "Low"
    )
  )
PatternExample
Two-way conditionif_else(revenue > 100, "High", "Other")
Multiple categoriescase_when(x < 0 ~ "Negative", x == 0 ~ "Zero", TRUE ~ "Positive")
Missing-value branchcase_when(is.na(x) ~ "Unknown", x > 0 ~ "Positive", TRUE ~ "Other")

See the case_when() tutorial for ordering conditions, missing values, and detailed examples.

10. Apply functions across multiple columns with across()

across() lets you apply the same function or set of functions to several columns inside verbs such as mutate() and summarise().

TaskSyntax
Apply a function to named columnsacross(c(units, revenue), mean)
Apply to numeric columnsacross(where(is.numeric), mean)
Apply several functionsacross(c(units, revenue), list(mean = mean, sum = sum))
Handle missing valuesacross(where(is.numeric), ~ mean(.x, na.rm = TRUE))
Set output namesacross(c(units, revenue), mean, .names = "mean_{.col}")
sales |>
  summarise(
    across(
      c(units, revenue),
      list(mean = ~ mean(.x), total = ~ sum(.x)),
      .names = "{.col}_{.fn}"
    )
  )

Learn more in the across() in R tutorial, including if_any() and if_all().

11. Join tables with dplyr

Join functions combine columns from two tables using matching key values. The key determines which rows match, and the join type determines which rows are retained.

FunctionRows retainedTypical use
left_join(x, y, by = "id")All rows from x, plus matching columns from yKeep every customer and attach order information
inner_join(x, y, by = "id")Only rows with matches in both tablesKeep records present in both datasets
right_join(x, y, by = "id")All rows from y, plus matching columns from xKeep every row in the second table
full_join(x, y, by = "id")All rows from both tablesCombine all keys, including unmatched records
semi_join(x, y, by = "id")Rows from x that have a match in yFilter x to keys found in y
anti_join(x, y, by = "id")Rows from x with no match in yFind records missing from the lookup table
customers |>
  left_join(orders, by = "customer_id")

customers |>
  anti_join(orders, by = "customer_id")

If key names differ, use by = c("customer_id" = "id"). Check for duplicate keys before joining: multiple matches can increase the number of output rows. See the dplyr joins tutorial.

12. Select rows by position or value

Use the slice_* functions when you need rows by position, extreme values, or a random sample.

TaskSyntaxUse
Choose row positionsslice(1:3)Keep rows 1 to 3
First n rowsslice_head(n = 5)Keep the first five rows
Last n rowsslice_tail(n = 3)Keep the last three rows
Largest valuesslice_max(revenue, n = 3)Keep rows with the three largest revenue values, including ties by default
Smallest valuesslice_min(revenue, n = 3)Keep rows with the three smallest revenue values, including ties by default
Random sample of rowsslice_sample(n = 2)Select a random sample of two rows
Sample a proportionslice_sample(prop = 0.25)Select about one quarter of the rows
# Top 3 products by revenue
sales |> slice_max(revenue, n = 3)

# Three random rows, reproducibly
set.seed(42)
sales |> slice_sample(n = 3)

To choose the top items separately within each category, use group_by(region) |> slice_max(revenue, n = 1). See the slice() in R guide.

13. Ranking, lagging and cumulative values

These functions calculate row-level values using other observations, often within a group. Sort first whenever the order of rows matters.

TaskSyntaxNotes
Previous valuelag(revenue)Returns the preceding observation
Next valuelead(revenue)Returns the following observation
Unique rankrow_number(desc(revenue))Assigns a unique position based on descending revenue
Rank with gaps after tiesmin_rank(desc(revenue))Equal values share a rank
Rank without gapsdense_rank(desc(revenue))Equal values share a rank; no gaps
Running totalcumsum(revenue)Accumulates values in current row order
Running minimumcummin(revenue)Smallest value seen so far
Running maximumcummax(revenue)Largest value seen so far
Group average alongside rowsmutate(group_mean = mean(revenue)) after group_by(region)Keeps the original rows and adds the group mean
sales |>
  arrange(product) |>
  group_by(product) |>
  mutate(
    previous_revenue = lag(revenue),
    running_revenue = cumsum(revenue)
  ) |>
  ungroup()

For detailed ranking, lead/lag, cumulative calculations, and time-series examples, read the dplyr window functions guide.

14. Missing values and useful helpers

Missing-value handling depends on the operation. Use explicit checks and decide whether missing values should be excluded, retained, or assigned a meaningful label.

TaskSyntaxResult
Find missing valuesfilter(is.na(revenue))Keep rows with missing revenue
Remove missing valuesfilter(!is.na(revenue))Keep rows with known revenue
Replace missing values in a columnmutate(revenue = coalesce(revenue, 0))Use zero wherever revenue is missing
Ignore missing values in a meanmean(revenue, na.rm = TRUE)Calculate the mean of observed values
Count non-missing valuessum(!is.na(revenue))Count known values
Check any condition is trueif_any(c(units, revenue), ~ .x > 100)TRUE when any selected column matches
Check all conditions are trueif_all(c(units, revenue), ~ .x > 0)TRUE when all selected columns match

Analysis tip: replacing missing values with zero is not always appropriate. A missing value may mean “not recorded” rather than “none.” Choose a rule based on the meaning of the variable and document it.

15. Common dplyr recipes

These short pipelines combine several verbs to complete common data-analysis tasks.

Recipe A: Keep high-revenue sales and show selected columns

sales |>
  filter(revenue > 100) |>
  select(product, region, revenue) |>
  arrange(desc(revenue))

Recipe B: Total revenue by region

sales |>
  group_by(region) |>
  summarise(total_revenue = sum(revenue), .groups = "drop") |>
  arrange(desc(total_revenue))

Recipe C: Add a category based on revenue

sales |>
  mutate(category = case_when(
    revenue >= 130 ~ "High",
    revenue >= 100 ~ "Medium",
    TRUE ~ "Low"
  ))

Recipe D: Find the best-selling row in each region

sales |>
  group_by(region) |>
  slice_max(revenue, n = 1) |>
  ungroup()

Recipe E: Count product sales by region

sales |>
  count(region, product, sort = TRUE)

Recipe F: Create a compact numeric summary

sales |>
  summarise(
    across(
      where(is.numeric),
      list(mean = ~ mean(.x, na.rm = TRUE),
           max = ~ max(.x, na.rm = TRUE)),
      .names = "{.col}_{.fn}"
    )
  )

16. Quick dplyr function reference

Use this final table when you know what you want to do but need to remember the function name.

GoalFunctionRemember
Choose columnsselect()Columns, not rows
Choose rows by conditionsfilter()Logical conditions
Add or change columnsmutate()Usually preserves row count
Sort rowsarrange()Use desc() for descending order
Rename columnsrename()new_name = old_name
Group observationsgroup_by()Sets groups for later verbs
Summarise datasummarise()Usually reduces rows per group
Count categoriescount()Convenient frequency table
Find unique rowsdistinct()Can use more than one key column
Conditional categoriescase_when()Specific conditions first
Apply functions to many columnsacross()Commonly used in mutate/summarise
Combine tablesleft_join(), inner_join(), etc.Choose the correct matching key and join type
Choose rows by position/valueslice(), slice_max()Useful for first, last, top, and bottom rows
Compare observations across rowslag(), lead()Sort first when order matters
Remove groupingungroup()Useful after grouped calculations

Recommended dplyr tutorials by topic

Use these in-depth guides when you need more than a quick reminder.

dplyr FAQ

What is dplyr in R?

dplyr is an R package for data manipulation. Its main functions help you select columns, filter rows, create or change variables, sort observations, summarise groups, and combine tables.

What are the most useful dplyr functions?

Commonly used functions include select(), filter(), mutate(), arrange(), rename(), summarise(), group_by(), count(), distinct(), across(), and the join functions such as left_join().

How do I use the dplyr cheat sheet?

Choose the topic that matches your task, read the function summary, and adapt the example to your column names. The examples use the native R pipe |> and can be run after loading dplyr.

What is the difference between filter() and select() in dplyr?

filter() chooses rows based on conditions, while select() chooses columns. Use filter() for records that meet a rule and select() for the variables you want to keep.

What is the difference between mutate() and summarise()?

mutate() creates or changes columns while generally retaining the number of rows. summarise() calculates summary values and usually returns one row per group.

Do I need to install dplyr before using this cheat sheet?

Yes, install the package once with install.packages("dplyr") if it is not already installed. Then load it in each R session with library(dplyr).

Can I use dplyr with a data frame?

Yes. dplyr works with data frames and tibbles, and its verbs can be combined into readable data-processing pipelines.

Key takeaways

  • Use select() for columns and filter() for rows.
  • Use mutate() to create or transform columns and summarise() to calculate summaries.
  • Use group_by() before grouped calculations and ungroup() when grouping is no longer needed.
  • Use the join function that matches your row-retention goal, and check whether join keys are unique.
  • Sort data explicitly before order-dependent calculations such as lag(), lead(), and cumsum().

For a structured introduction, return to the dplyr tutorial overview and work through each topic in order.