dplyr Cheat Sheet for R: Topic-by-Topic Reference
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)
)
| Syntax | Meaning | Example |
|---|---|---|
|> | Pass the result on the left to the next operation | sales |> filter(units > 8) |
%>% | Pipe from the magrittr package, commonly used in older dplyr code | sales %>% filter(units > 8) |
group_by() | Define groups for later calculations | group_by(region) |
ungroup() | Remove grouping from a grouped data frame | ungroup() |
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.
| Task | Syntax | What it does |
|---|---|---|
| Keep named columns | select(product, revenue) | Keep only product and revenue |
| Keep a range | select(product:units) | Keep columns from product through units in their current order |
| Exclude a column | select(-region) | Keep every column except region |
| Select by prefix | select(starts_with("rev")) | Keep columns whose names start with rev |
| Select by suffix | select(ends_with("id")) | Keep columns whose names end with id |
| Select by name pattern | select(contains("sale")) | Keep columns whose names contain sale |
| Select numeric columns | select(where(is.numeric)) | Keep columns that satisfy is.numeric |
| Rename while selecting | select(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.
| Task | Syntax | Meaning |
|---|---|---|
| Greater than | filter(revenue > 100) | Keep revenue above 100 |
| Equal to text | filter(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 list | filter(product %in% c("Tea", "Juice")) | Keep Tea or Juice |
| Exclude a value | filter(product != "Tea") | Remove Tea rows |
| Between limits | filter(between(revenue, 75, 140)) | Keep values from 75 through 140, inclusive |
| Missing values | filter(is.na(revenue)) | Keep rows with missing revenue |
| Non-missing values | filter(!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.
| Task | Syntax | Result |
|---|---|---|
| Add a calculated column | mutate(profit = revenue - cost) | Creates profit |
| Calculate a ratio | mutate(revenue_per_unit = revenue / units) | Revenue divided by units |
| Change units | mutate(revenue_k = revenue / 1000) | Revenue expressed in thousands |
| Replace an existing column | mutate(revenue = revenue * 1.05) | Overwrites revenue with adjusted values |
| Use an earlier new column | mutate(total = units * 10, tax = total * 0.1) | tax uses total calculated in the same mutate() |
| Create a logical flag | mutate(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.
| Task | Syntax |
|---|---|
| Ascending order | arrange(revenue) |
| Descending order | arrange(desc(revenue)) |
| Sort by multiple columns | arrange(region, desc(revenue)) |
| Put missing values last explicitly | arrange(is.na(revenue), revenue) |
| Sort within groups for a later calculation | arrange(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)
| Task | Syntax |
|---|---|
| Rename one column | rename(sales_total = revenue) |
| Rename multiple columns | rename(item = product, area = region) |
| Rename while choosing columns | select(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.
| Task | Syntax |
|---|---|
| Total by region | group_by(region) |> summarise(total = sum(revenue)) |
| Average by product | group_by(product) |> summarise(avg = mean(revenue)) |
| Count rows per group | group_by(region) |> summarise(n = n()) |
| Multiple statistics | summarise(total = sum(revenue), average = mean(revenue)) |
| Ignore missing values in sum | summarise(total = sum(revenue, na.rm = TRUE)) |
| Return an ungrouped result | summarise(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.
| Task | Syntax |
|---|---|
| Count rows by category | count(region) |
| Count combinations | count(region, product) |
| Sort counts descending | count(product, sort = TRUE) |
| Count unique values | n_distinct(product) |
| Count unique non-missing values | n_distinct(product, na.rm = TRUE) |
| Keep unique products | distinct(product) |
| Keep unique combinations | distinct(region, product) |
| Keep one row per key and retain other columns | distinct(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"
)
)
| Pattern | Example |
|---|---|
| Two-way condition | if_else(revenue > 100, "High", "Other") |
| Multiple categories | case_when(x < 0 ~ "Negative", x == 0 ~ "Zero", TRUE ~ "Positive") |
| Missing-value branch | case_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().
| Task | Syntax |
|---|---|
| Apply a function to named columns | across(c(units, revenue), mean) |
| Apply to numeric columns | across(where(is.numeric), mean) |
| Apply several functions | across(c(units, revenue), list(mean = mean, sum = sum)) |
| Handle missing values | across(where(is.numeric), ~ mean(.x, na.rm = TRUE)) |
| Set output names | across(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.
| Function | Rows retained | Typical use |
|---|---|---|
left_join(x, y, by = "id") | All rows from x, plus matching columns from y | Keep every customer and attach order information |
inner_join(x, y, by = "id") | Only rows with matches in both tables | Keep records present in both datasets |
right_join(x, y, by = "id") | All rows from y, plus matching columns from x | Keep every row in the second table |
full_join(x, y, by = "id") | All rows from both tables | Combine all keys, including unmatched records |
semi_join(x, y, by = "id") | Rows from x that have a match in y | Filter x to keys found in y |
anti_join(x, y, by = "id") | Rows from x with no match in y | Find 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.
| Task | Syntax | Use |
|---|---|---|
| Choose row positions | slice(1:3) | Keep rows 1 to 3 |
| First n rows | slice_head(n = 5) | Keep the first five rows |
| Last n rows | slice_tail(n = 3) | Keep the last three rows |
| Largest values | slice_max(revenue, n = 3) | Keep rows with the three largest revenue values, including ties by default |
| Smallest values | slice_min(revenue, n = 3) | Keep rows with the three smallest revenue values, including ties by default |
| Random sample of rows | slice_sample(n = 2) | Select a random sample of two rows |
| Sample a proportion | slice_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.
| Task | Syntax | Notes |
|---|---|---|
| Previous value | lag(revenue) | Returns the preceding observation |
| Next value | lead(revenue) | Returns the following observation |
| Unique rank | row_number(desc(revenue)) | Assigns a unique position based on descending revenue |
| Rank with gaps after ties | min_rank(desc(revenue)) | Equal values share a rank |
| Rank without gaps | dense_rank(desc(revenue)) | Equal values share a rank; no gaps |
| Running total | cumsum(revenue) | Accumulates values in current row order |
| Running minimum | cummin(revenue) | Smallest value seen so far |
| Running maximum | cummax(revenue) | Largest value seen so far |
| Group average alongside rows | mutate(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.
| Task | Syntax | Result |
|---|---|---|
| Find missing values | filter(is.na(revenue)) | Keep rows with missing revenue |
| Remove missing values | filter(!is.na(revenue)) | Keep rows with known revenue |
| Replace missing values in a column | mutate(revenue = coalesce(revenue, 0)) | Use zero wherever revenue is missing |
| Ignore missing values in a mean | mean(revenue, na.rm = TRUE) | Calculate the mean of observed values |
| Count non-missing values | sum(!is.na(revenue)) | Count known values |
| Check any condition is true | if_any(c(units, revenue), ~ .x > 100) | TRUE when any selected column matches |
| Check all conditions are true | if_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.
| Goal | Function | Remember |
|---|---|---|
| Choose columns | select() | Columns, not rows |
| Choose rows by conditions | filter() | Logical conditions |
| Add or change columns | mutate() | Usually preserves row count |
| Sort rows | arrange() | Use desc() for descending order |
| Rename columns | rename() | new_name = old_name |
| Group observations | group_by() | Sets groups for later verbs |
| Summarise data | summarise() | Usually reduces rows per group |
| Count categories | count() | Convenient frequency table |
| Find unique rows | distinct() | Can use more than one key column |
| Conditional categories | case_when() | Specific conditions first |
| Apply functions to many columns | across() | Commonly used in mutate/summarise |
| Combine tables | left_join(), inner_join(), etc. | Choose the correct matching key and join type |
| Choose rows by position/value | slice(), slice_max() | Useful for first, last, top, and bottom rows |
| Compare observations across rows | lag(), lead() | Sort first when order matters |
| Remove grouping | ungroup() | Useful after grouped calculations |
Recommended dplyr tutorials by topic
Use these in-depth guides when you need more than a quick reminder.
- R pipe operator: %>% and |> — connect operations into a readable workflow.
- select() in R — select, exclude, and rename columns.
- filter() in R — filter data with logical conditions.
- mutate() in R — create and transform variables.
- arrange() in R — sort data and order rows.
- rename() in R — rename variables clearly.
- group_by() and summarise() — calculate group-level statistics.
- count() and distinct() — count observations and unique values.
- case_when() in R — build conditional categories.
- across() in R — apply functions to multiple columns.
- dplyr joins — combine related datasets.
- slice() in R — select rows by position or value.
- Window functions in dplyr — rank values and compare observations.
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 andfilter()for rows. - Use
mutate()to create or transform columns andsummarise()to calculate summaries. - Use
group_by()before grouped calculations andungroup()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(), andcumsum().
For a structured introduction, return to the dplyr tutorial overview and work through each topic in order.