dplyr across(): Apply the Same Function to Multiple Columns at Once
across() applies the same function to multiple columns inside mutate() or summarise(). It replaced mutate_if, mutate_at, and mutate_all with one unified verb.
Before across, you wrote mutate(col1 = round(col1), col2 = round(col2), col3 = round(col3)). Now: mutate(across(c(col1, col2, col3), round)).
Basic: One Function, Multiple Columns
Column Selection Inside across()
Multiple Functions per Column
Use a named list to apply several functions, creating multiple output columns.
.names: Control Output Column Names
across in mutate: Transform Columns
if_any() and if_all(): across for filter
Practice Exercises
Exercise 1: Standardize All Numeric Columns
Z-score standardize every numeric column in iris.
Click to reveal solution
```rSummary
| Pattern | Code |
|---|---|
| All numeric | across(where(is.numeric), fn) |
| By name | across(c(col1, col2), fn) |
| By pattern | across(starts_with("x"), fn) |
| Multiple fns | across(cols, list(mean = mean, sd = sd)) |
| Custom names | .names = "{.fn}_{.col}" |
| Filter any | filter(if_any(cols, ~ .x > 5)) |
| Filter all | filter(if_all(cols, ~ .x > 5)) |
FAQ
What replaced mutate_at, mutate_if, mutate_all?
across() replaced all three in dplyr 1.0. mutate_if(is.numeric, fn) → mutate(across(where(is.numeric), fn)). mutate_at(vars(x,y), fn) → mutate(across(c(x,y), fn)).
Can I use across() in filter()?
Not directly. Use if_any() or if_all() instead: filter(if_any(cols, ~ .x > threshold)).
What's Next?
- dplyr filter & select — the parent tutorial
- dplyr mutate & rename — where across() is used most
- dplyr group_by & summarise — across in grouped summaries