dplyr across() in R: A Beginner-Friendly Guide with Examples
Learn how to use dplyr across() in R to work with several columns at once. Follow beginner examples, then apply across() in mutate(), summarise(), grouped analysis, data cleaning, and reusable functions.
What does across() do in R?
across() is a dplyr function for applying the same operation to multiple columns in a data frame. Instead of writing separate expressions for every variable, you select the columns once and tell R which function to apply.
For example, imagine a sales dataset with columns named sales, cost, and profit. If you want the mean of all three columns, you could calculate each mean separately. With across(), you can write one concise expression and let dplyr handle the selected variables.
library(dplyr)
data |>
summarise(across(c(sales, cost, profit), mean))
across() is usually used inside verbs such as mutate() and summarise():
mutate(across(...))transforms existing columns or creates transformed columns.summarise(across(...))calculates summaries for selected columns.if_any()andif_all()use a similar column-selection idea to create a single logical result for each row.
Beginner tip: across() does not replace mutate() or summarise(). It works inside those functions to specify which columns should receive an operation. If you need a refresher, see mutate() in R and group_by() and summarise().
Create example data for across()
We will use a small sales dataset with a region, salesperson, sales revenue, profit, number of orders, and customer rating. It is deliberately small so you can follow each transformation and understand how the selected columns change.
library(dplyr)
sales_data <- tibble(
region = c("North", "North", "South", "South", "East", "East", "West", "West"),
salesperson = c("Amina", "Bilal", "Sara", "Omar", "Noor", "Hassan", "Maya", "Zain"),
sales = c(1200, 950, 1450, 800, 1100, 700, 1600, 1050),
profit = c(260, 180, 310, 120, 240, 90, 390, 210),
orders = c(14, 11, 18, 9, 13, 8, 20, 12),
rating = c(4, 3, 5, 2, 4, 2, 5, 3)
)
sales_data
| region | salesperson | sales | profit | orders | rating |
|---|---|---|---|---|---|
In this table, sales, profit, orders, and rating are numeric measures. We will select different combinations of these columns to calculate summaries and create new variables.
Your first across() example
Suppose you want to calculate the average sales, average profit, and average number of orders. Without across(), you might write:
sales_data |>
summarise(
average_sales = mean(sales),
average_profit = mean(profit),
average_orders = mean(orders)
)
That works, but you repeat the same function three times. With across(), select the columns and apply mean once:
sales_data |>
summarise(across(c(sales, profit, orders), mean))
This returns one row with the mean of each selected column. By default, the output columns retain the original column names. This is useful when you want the same summary statistic for many variables.
What each part means
summarise()reduces the data to summary values.across()identifies the columns and applies the requested function to each one.c(sales, profit, orders)selects the three columns by name.meanis the function applied to every selected column.
Select columns to transform with across()
The first argument to across() is a column selection. dplyr uses tidyselect syntax, so you can select columns by name, range, prefix, suffix, or type.
Select specific columns
sales_data |>
summarise(across(c(sales, profit), mean))
Use c() when the columns you need are not next to one another.
Select a range of columns
sales_data |>
summarise(across(sales:rating, mean))
This selects every column from sales through rating in the data frame's column order. Because the range includes the numeric measures in this example, it is appropriate here. Check the column order before using ranges on a larger dataset.
Select columns by name pattern
# Select columns whose names start with "sale"
sales_data |>
summarise(across(starts_with("sale"), mean))
# Select columns whose names contain "fit"
sales_data |>
summarise(across(contains("fit"), mean))
Other helpful selectors include ends_with(), matches(), everything(), all_of(), and any_of(). These are especially useful when datasets contain many columns or when a vector stores the column names you want to select.
measure_columns <- c("sales", "profit", "orders")
sales_data |>
summarise(across(all_of(measure_columns), mean))
all_of() expects every listed column to exist and will report an error if one is missing. any_of() selects the listed columns that are present, which can be useful in flexible data-cleaning workflows.
Use across() inside mutate()
Use mutate() when you want to transform values while keeping the rows of the dataset. For example, you might convert several financial variables from dollars to thousands of dollars, round multiple measures, or standardise selected numeric columns.
Multiply several columns by the same value
Suppose sales and profit are recorded in dollars and you want additional columns in thousands of dollars. One clear approach is to create new columns with .names:
sales_data |>
mutate(across(
c(sales, profit),
~ .x / 1000,
.names = "{.col}_thousands"
))
Here, .x represents the current column's values. The result adds sales_thousands and profit_thousands, while preserving the original columns.
Round multiple columns
sales_data |>
mutate(across(c(sales, profit), round, digits = 0))
This example rounds the selected columns to zero decimal places. Since the example values are already whole numbers, the visible values will not change; the same pattern is useful for measurements with decimal values.
Standardise selected variables
sales_data |>
mutate(across(c(sales, profit, orders), ~ as.numeric(scale(.x)),
.names = "{.col}_z"))
scale() centres a numeric vector and scales it by its standard deviation by default. Converting the result with as.numeric() removes the matrix-like structure returned by scale(). This pattern can be useful before some statistical or machine-learning workflows, but standardisation should be chosen based on the meaning of your variables and the requirements of your model.
Important: mutate(across(...)) changes every selected column. If you want to preserve the original values, use .names = "{.col}_new" or another naming pattern to create separate output columns.
Use across() inside summarise()
summarise() is used to produce summary statistics rather than retaining every original row. Combining it with across() is a common way to explore a dataset efficiently.
Calculate the mean for several columns
sales_data |>
summarise(across(c(sales, profit, orders, rating), mean))
Calculate totals for several measures
sales_data |>
summarise(across(c(sales, profit, orders), sum))
Use sum when a total is meaningful for the variable. A total customer rating, for example, is usually less informative than the average rating, so choose functions based on the question you are trying to answer.
Calculate minimum and maximum values
sales_data |>
summarise(across(
c(sales, profit, orders),
list(minimum = min, maximum = max)
))
This applies both functions to each selected column. dplyr creates separate output columns for the minimum and maximum of each variable. The default names combine the source column and function label, such as sales_minimum and sales_maximum.
Calculate several descriptive statistics
sales_data |>
summarise(across(
c(sales, profit, orders),
list(
mean = mean,
median = median,
sd = sd,
minimum = min,
maximum = max
)
))
This produces a compact descriptive-statistics table for each selected variable. It is useful in exploratory data analysis, report preparation, and initial checks before modelling.
Apply multiple functions with across()
You can pass a named list of functions to the second argument of across(). This is more efficient than writing a separate summary expression for every combination of variable and statistic.
sales_data |>
summarise(across(
c(sales, profit),
list(
average = mean,
median = median,
total = sum
)
))
The named list tells dplyr to calculate three results for each selected column. The names in the list are used to identify each statistic in the output. Use descriptive names because they make summary tables easier to interpret and export.
Pass arguments to the function
Additional arguments can be passed after the function list. For example, when a column contains missing values, use na.rm = TRUE to calculate a statistic from the available values:
survey_data |>
summarise(across(
c(satisfaction, trust, service_quality),
mean,
na.rm = TRUE
))
This example assumes that survey_data contains the three named numeric columns. The argument na.rm = TRUE is passed to mean(). Whether removing missing values is appropriate depends on your analysis; do not automatically discard missingness without considering what it represents.
Use a different function for each column
across() is best when the same function or list of functions applies to each selected column. If one column needs a mean and another needs a median, use separate expressions or create a custom workflow that explicitly reflects those different requirements.
sales_data |>
summarise(
average_sales = mean(sales),
median_profit = median(profit),
total_orders = sum(orders)
)
Clear, explicit code is preferable to forcing unlike operations into a complicated expression.
Control output column names with .names
By default, across() uses the source column name when applying one function. When you apply multiple functions, output names combine the column name and function name. The .names argument lets you define a consistent naming pattern.
Add a prefix to output columns
sales_data |>
summarise(across(
c(sales, profit),
mean,
.names = "mean_{.col}"
))
This creates columns such as mean_sales and mean_profit.
Add a suffix to transformed columns
sales_data |>
mutate(across(
c(sales, profit),
~ .x * 1.10,
.names = "{.col}_with_10pct_increase"
))
This adds new columns showing a hypothetical 10% increase. It is a scenario calculation, not a claim that actual sales or profit will rise by that amount.
Include the function name in the output
sales_data |>
summarise(across(
c(sales, profit),
list(mean = mean, sd = sd),
.names = "{.fn}_{.col}"
))
The placeholders are:
{.col}is replaced by the selected column name.{.fn}is replaced by the name of the function from the named list.
For example, {.fn}_{.col} creates names such as mean_sales and sd_profit. Choose one naming convention and use it consistently across your project.
Select columns by type with where()
On real datasets, there may be dozens or hundreds of columns. You may not want to list every numeric variable by hand. Use where() with a predicate function to select columns by their properties.
Apply a function to all numeric columns
sales_data |>
summarise(across(where(is.numeric), mean))
This selects all numeric columns, including rating. That may be suitable for exploratory analysis, but it is not always appropriate to apply a numeric operation to every numeric field. Numeric IDs, postal codes, and coded categories can be numeric without being meaningful measurements.
Exclude a numeric identifier
# Suppose customer_id is numeric but should not be averaged.
customer_data |>
summarise(across(where(is.numeric) & !customer_id, mean))
Use column selectors deliberately. You can also select known measurement columns explicitly when the dataset contains identifiers or coded variables that should not be summarised.
Select columns by naming convention
survey_data |>
summarise(across(ends_with("_score"), mean, na.rm = TRUE))
If survey variables consistently end with _score, this pattern helps apply the same summary to every score column. Naming conventions are especially useful for repeated survey instruments and analytical datasets.
Use across() with grouped data
Combine group_by(), summarise(), and across() to calculate statistics for each category. For example, a sales manager may want average revenue and profit by region rather than one overall average.
Calculate average sales and profit by region
sales_data |>
group_by(region) |>
summarise(across(c(sales, profit), mean), .groups = "drop")
The output contains one row for each region and the mean of each selected measure within that region. .groups = "drop" removes grouping from the result, which can make the next step of a pipeline easier to reason about.
Calculate several statistics by group
sales_data |>
group_by(region) |>
summarise(
across(
c(sales, profit),
list(mean = mean, total = sum, maximum = max)
),
.groups = "drop"
)
This produces a regional summary containing mean, total, and maximum values for sales and profit. It is useful for comparing performance across regions, branches, departments, product categories, or time periods.
Transform several columns within each group
sales_data |>
group_by(region) |>
mutate(across(
c(sales, profit),
~ .x / sum(.x),
.names = "{.col}_share_of_region"
)) |>
ungroup()
Within each region, this calculates each salesperson's share of that region's total sales and profit. Because the data is grouped, sum(.x) is calculated within the current region rather than across the whole dataset. The resulting shares can help compare contributions within each region.
Handle missing values with across()
Many real datasets contain missing values. Functions such as mean() return NA when missing values are present unless you tell the function how to handle them. Use na.rm = TRUE when your analysis should calculate the statistic from non-missing observations.
survey_data |>
summarise(across(
c(satisfaction, trust, service_quality),
~ mean(.x, na.rm = TRUE)
))
Using a lambda expression such as ~ mean(.x, na.rm = TRUE) makes the argument explicit. In a simple call, you can also pass na.rm = TRUE directly to across().
Count missing values in multiple columns
survey_data |>
summarise(across(
c(satisfaction, trust, service_quality),
~ sum(is.na(.x)),
.names = "missing_{.col}"
))
This creates one count per selected column, making it easy to identify variables that need further data-quality checks.
Replace missing values in selected columns
survey_data |>
mutate(across(
c(satisfaction, trust, service_quality),
~ tidyr::replace_na(.x, 0)
))
This example replaces missing values with zero. Only do this when zero is a defensible replacement for your data and research question. In many surveys, a missing answer is not the same as a zero rating; retaining missing values or using a more appropriate imputation strategy may be better.
Practical business analytics examples
across() is useful when you need consistent calculations across many measures. The following examples show how the same pattern can support finance, marketing, operations, survey analysis, and data preparation.
1. Finance: calculate descriptive statistics for financial measures
financial_data |>
summarise(across(
c(revenue, expenses, profit, cash_flow),
list(mean = mean, median = median, sd = sd),
na.rm = TRUE
))
Use this to inspect typical values and variability across financial measures. Ensure the selected columns use compatible units and that the statistics make sense for each measure.
2. Marketing: summarise campaign metrics
campaign_data |>
group_by(channel) |>
summarise(across(
c(impressions, clicks, conversions, spend),
sum,
na.rm = TRUE
), .groups = "drop")
This totals impressions, clicks, conversions, and spend by marketing channel. Metrics such as click-through rate and conversion rate are usually calculated from totals (for example, total clicks divided by total impressions), rather than by blindly averaging rates from individual rows.
3. Operations: compare service and processing times
operations_data |>
group_by(team) |>
summarise(across(
c(wait_minutes, processing_minutes, resolution_minutes),
list(mean = mean, median = median, maximum = max),
na.rm = TRUE
), .groups = "drop")
These summaries can help teams compare typical service times and identify unusually high values. For strongly skewed time data, the median may describe a typical case more accurately than the mean.
4. Survey analysis: compute average scores
survey_data |>
group_by(department) |>
summarise(across(
c(job_satisfaction, leadership_trust, work_engagement),
~ mean(.x, na.rm = TRUE)
), .groups = "drop")
This calculates department-level average scores. Before interpreting the results, confirm that the score direction and scale are consistent and that the amount of missing data is acceptable.
5. Data preparation: standardise multiple predictors
model_data |>
mutate(across(
c(age, annual_income, transaction_count),
~ as.numeric(scale(.x)),
.names = "{.col}_scaled"
))
This creates standardised versions of three predictors while keeping the original columns. In a predictive modelling workflow, calculate scaling parameters on the training data and apply those same parameters to validation or test data to avoid data leakage.
Use custom functions and lambda expressions
Sometimes the operation you want is not a built-in function, or you want to control how it is applied. In across(), .x represents the current selected column inside a lambda expression.
Calculate the range of each selected column
sales_data |>
summarise(across(
c(sales, profit, orders),
~ max(.x) - min(.x),
.names = "range_{.col}"
))
The expression calculates the difference between the maximum and minimum value of each selected column.
Convert selected text columns to lowercase
customer_data |>
mutate(across(where(is.character), tolower))
This transforms all character columns to lowercase. It can help standardise inconsistent text values before joining or counting categories, but it may not be appropriate for names or labels where original capitalisation matters.
Trim extra spaces from text columns
customer_data |>
mutate(across(where(is.character), trimws))
trimws() removes whitespace at the beginning and end of strings. For example, "North " and "North" would otherwise be treated as different text values in many operations.
Write a reusable function
round_measurements <- function(data, columns) {
data |>
mutate(across(all_of(columns), ~ round(.x, 2)))
}
round_measurements(
sales_data,
c("sales", "profit")
)
A helper function is helpful when the same transformation is used in multiple scripts or reports. The all_of(columns) selector makes the function apply to the supplied column names and report an error if a requested column is absent.
Understand if_any() and if_all()
if_any() and if_all() are related to across(), but they return one logical value per row rather than separate transformed columns. They are often used inside filter() to keep rows that satisfy conditions across several columns.
Keep rows where any selected score is below 50
exam_data |>
filter(if_any(c(math_score, english_score, science_score), ~ .x < 50))
This keeps a row if at least one of the three scores is below 50.
Keep rows where all selected scores are at least 50
exam_data |>
filter(if_all(c(math_score, english_score, science_score), ~ .x >= 50))
This keeps a row only if all three selected scores meet the threshold. As with other logical operations, consider how missing values should be handled in your dataset.
Flag records with a missing value in any selected column
customer_data |>
mutate(has_missing_contact = if_any(
c(email, phone, address),
is.na
))
This creates a logical flag indicating whether any of the selected contact fields are missing. It is useful for data-quality checks and follow-up workflows.
across() versus older scoped verbs
Older dplyr code may use functions such as summarise_at(), mutate_at(), summarise_if(), or mutate_if(). In modern dplyr, across() provides a consistent way to select columns and apply functions inside the main verbs.
| Task | Modern pattern | Purpose |
|---|---|---|
| Summarise named columns | summarise(across(c(a, b), mean)) | Apply a summary to selected variables |
| Transform named columns | mutate(across(c(a, b), log1p)) | Transform values while retaining rows |
| Summarise numeric columns | summarise(across(where(is.numeric), mean)) | Select columns by type |
| Test conditions across columns | filter(if_any(c(a, b), predicate)) | Keep rows where any selected column matches |
For new code, learn the across() pattern first. When maintaining older scripts, check the dplyr version and documentation before changing established code.
Common across() errors and how to fix them
1. Using across() outside a dplyr verb
Problem: calling across() on its own, without a context such as mutate() or summarise().
Solution: place it inside a suitable dplyr verb:
sales_data |>
summarise(across(c(sales, profit), mean))
2. Selecting a column that does not exist
Problem: a misspelled column name or a name that differs from the actual dataset.
Solution: inspect the column names with names(sales_data) or glimpse(sales_data), then update the selection. Remember that all_of() errors when a requested name is missing.
3. Applying numeric functions to non-numeric columns
Problem: using mean on character data or including an identifier in a numeric selection.
Solution: select appropriate numeric measures, for example across(c(sales, profit), mean), or use where(is.numeric) only after checking what the numeric columns represent.
4. Unexpected missing summary values
Problem: a summary returns NA because the selected column contains missing values.
Solution: when appropriate, use mean(.x, na.rm = TRUE) or another function-specific missing-value strategy. Do not remove missing values without considering their meaning.
5. Overwriting original columns unintentionally
Problem: mutate(across(...)) writes the transformed values back into the selected columns.
Solution: use .names to create new columns:
sales_data |>
mutate(across(c(sales, profit), ~ .x * 1.1,
.names = "{.col}_scenario"))
6. Confusing grouped and ungrouped results
Problem: a calculation inside grouped data is performed separately for each group, which may differ from an overall calculation.
Solution: check whether group_by() is active. Use ungroup() or .groups = "drop" when you want to remove grouping after a summary.
Practice exercises
Try these exercises with the sales_data dataset above. Expand each answer when you are ready to check your code.
Exercise 1: Calculate average sales and profit
Use summarise() and across() to calculate the mean of sales and profit.
Show answer
sales_data |>
summarise(across(c(sales, profit), mean))
Exercise 2: Calculate three statistics
For sales and profit, calculate the mean, median, and maximum using a named list of functions.
Show answer
sales_data |>
summarise(across(
c(sales, profit),
list(mean = mean, median = median, maximum = max)
))
Exercise 3: Add a 10% scenario column
Create new columns for sales and profit after a hypothetical 10% increase. Keep the original columns unchanged.
Show answer
sales_data |>
mutate(across(
c(sales, profit),
~ .x * 1.10,
.names = "{.col}_scenario"
))
Exercise 4: Summarise each region
Calculate the total sales and total profit for each region.
Show answer
sales_data |>
group_by(region) |>
summarise(across(c(sales, profit), sum), .groups = "drop")
Exercise 5: Count missing values
For a hypothetical survey_data dataset, count missing values in the columns satisfaction, trust, and service_quality.
Show answer
survey_data |>
summarise(across(
c(satisfaction, trust, service_quality),
~ sum(is.na(.x)),
.names = "missing_{.col}"
))
dplyr FAQ
What does across() do in dplyr?
across() applies one or more functions to a selected set of columns inside dplyr verbs such as mutate() and summarise(). It reduces repeated code when you need the same operation on multiple variables.
How do I use across() in R?
Place across() inside a dplyr verb and select columns with tidyselect helpers. For example, summarise(across(c(sales, profit), mean, na.rm = TRUE)) calculates means for both selected columns.
What is the difference between across() and mutate()?
mutate() creates or changes columns, while across() specifies which columns to operate on and which function to apply. They are often used together, such as mutate(across(where(is.numeric), scale)).
Can across() apply different functions to multiple columns?
Yes. Use a named list of functions, such as across(c(sales, profit), list(mean = mean, total = sum), na.rm = TRUE). The output names combine the original column name and function name by default.
How do I select numeric columns with across()?
Use across(where(is.numeric), function_name) to select columns whose data type is numeric. Be careful to exclude identifier columns that happen to be stored as numbers.
Can I use across() with group_by() and summarise()?
Yes. Group the data first, then use summarise(across(...)) to calculate statistics for selected columns within each group.
How do I rename columns created by across()?
Use the .names argument, for example across(c(sales, profit), mean, .names = "mean_{.col}"). The { .col } placeholder is replaced by each selected column name.
What replaced the older summarise_at(), mutate_at(), and similar functions?
across() is the modern, consistent approach for applying functions to selected columns within dplyr verbs. Older scoped verbs are superseded in modern dplyr workflows.
Key points to remember
across()applies functions to multiple selected columns inside dplyr verbs.- Use
mutate(across(...))to transform columns andsummarise(across(...))to calculate summary statistics. - Select columns by name, range, pattern, or type using tidyselect helpers such as
where(is.numeric). - Use a named list of functions to calculate several statistics for each column.
- Use
.names,{.col}, and{.fn}to make output column names clear. - Check missing values, data types, grouping, and the meaning of each variable before applying transformations.
- Use
if_any()andif_all()when you need one logical result per row across multiple columns.
Next, learn how to join tables in dplyr to combine information from different datasets. You can also revisit mutate(), group_by() and summarise(), and the dplyr tutorial overview for the complete learning path.