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 group_by() and summarise(): Group Data in R

Updated

Learn how to group data in R with dplyr group_by() and summarise(). Start with a simple total, then calculate group averages, summaries by multiple variables, percentages, and advanced grouped results.

What do group_by() and summarise() do in R?

group_by() and summarise() are two of the most useful functions in the dplyr package for data analysis in R. They let you divide a dataset into meaningful groups and calculate a summary for each group. Typical summaries include totals, averages, row counts, minimums, maximums and other statistics.

For example, a shop may have thousands of transactions. Instead of looking at every transaction individually, you might want to know total sales by region, average sale by product, or the number of transactions in each region. Grouping and summarising make these questions straightforward to answer.

data |>
  group_by(group_column) |>
  summarise(summary_value = sum(value_column))

The basic idea is simple:

  • group_by() defines which rows belong together.
  • summarise() calculates one or more summary values for each group.
  • The pipe |> passes the result from one step to the next.

Remember: group_by() does not itself calculate totals or averages. It establishes the groups. summarise() performs the calculation.

Create sample data for the examples

We will use a small sales dataset with a region, product, sales amount and number of units. The same code can be adapted to real sales files, survey results, student marks, healthcare records or other tabular data.

library(dplyr)

sales_data <- tibble(
  region = c("East", "West", "East", "West", "East",
             "South", "South", "East", "West", "South"),
  product = c("Laptop", "Laptop", "Phone", "Phone", "Laptop",
              "Phone", "Laptop", "Phone", "Laptop", "Phone"),
  sales = c(1200, 1500, 800, 950, 900, 700, 1100, 650, 1800, 850),
  units = c(3, 4, 5, 6, 2, 4, 3, 3, 5, 5)
)

sales_data
Example sales data: one row per transaction
regionproductsalesunits
EastLaptop12003
WestLaptop15004
EastPhone8005
WestPhone9506
EastLaptop9002
SouthPhone7004
SouthLaptop11003
EastPhone6503
WestLaptop18005
SouthPhone8505

Each row represents a transaction. The sales column contains the sales amount, and units records how many items were sold in that transaction. The data is deliberately small so that you can check the calculations by hand.

1. Your first group_by() example

Start by grouping the rows by region:

sales_data |>
  group_by(region)

This marks the data as grouped by region, but it does not yet reduce the number of rows or calculate a summary. You still have the transaction-level data. To answer a question such as “What are total sales in each region?”, add summarise().

2. Calculate total sales by group

A common first task is to calculate the sum by group in R. Use sum() inside summarise():

sales_data |>
  group_by(region) |>
  summarise(total_sales = sum(sales), .groups = "drop")
Total sales by region
regiontotal_sales
East3550
West4250
South2650

Here is what each part means:

  • group_by(region) creates a group for East, West and South.
  • sum(sales) adds the sales amounts within the current group.
  • total_sales = gives the result column a clear name.
  • .groups = "drop" returns an ordinary, ungrouped result.

To calculate total units sold instead, change the summary expression:

sales_data |>
  group_by(region) |>
  summarise(total_units = sum(units), .groups = "drop")

You can group by any categorical variable, such as department, country, school, customer type, month or product category. The important thing is that each group answers a useful question.

3. Calculate averages, minimums and maximums

Summaries are not limited to totals. R's mean(), min() and max() functions work naturally inside summarise().

Average sales by region

sales_data |>
  group_by(region) |>
  summarise(average_sales = mean(sales), .groups = "drop")

This calculates the mean transaction amount within each region, rather than the mean of the regional totals. These are different measures: use a total to compare overall volume and an average to compare a typical transaction.

Smallest and largest transaction in each region

sales_data |>
  group_by(region) |>
  summarise(
    smallest_sale = min(sales),
    largest_sale = max(sales),
    .groups = "drop"
  )

These summaries can help identify differences in transaction size. In a real analysis, also consider the number of transactions in each region, since a region with very few observations may have an unstable average or range.

4. Calculate multiple summaries at once

You do not need a separate pipeline for every statistic. Include multiple named expressions inside one summarise() call:

sales_data |>
  group_by(region) |>
  summarise(
    total_sales = sum(sales),
    average_sales = mean(sales),
    transaction_count = n(),
    units_sold = sum(units),
    .groups = "drop"
  )
Regional sales summary
regiontotal_salestransactionsunits_sold
East3550413
West4250315
South2650312

The n() function returns the number of rows in the current group. In this example, it counts transactions in each region. The result is a compact report that combines sales volume, transaction frequency and units sold.

You can also round an average for presentation:

sales_data |>
  group_by(product) |>
  summarise(
    average_sale = round(mean(sales), 2),
    .groups = "drop"
  )

Rounding changes how the result is displayed numerically; for formal calculations, it is often better to keep full precision until the final report.

5. Group by more than one column

Sometimes one grouping variable is not enough. To compare each product within each region, pass both column names to group_by():

sales_data |>
  group_by(region, product) |>
  summarise(
    total_sales = sum(sales),
    transactions = n(),
    .groups = "drop"
  )
Total sales for each region-product combination
regionproducttotal_salestransactions
EastLaptop21002
WestLaptop33002
EastPhone14502
WestPhone9501
SouthPhone15502
SouthLaptop11001

R calculates a separate result for every observed combination of region and product. This is useful for questions such as which product sells best in each region, how marks vary by course and class, or how customer activity differs by country and customer segment.

Group by year and month

For time-based analysis, first ensure that your date column is stored as a Date or date-time value. You can then create date parts and summarise them. For example, with a data frame called orders that contains a Date column called order_date:

orders |>
  mutate(
    year = format(order_date, "%Y"),
    month = format(order_date, "%m")
  ) |>
  group_by(year, month) |>
  summarise(monthly_sales = sum(sales), .groups = "drop")

This example assumes order_date is already a valid date and sales is numeric. For a more detailed date workflow, check the time zone and date format before grouping; text dates can sort incorrectly if their formats are inconsistent.

6. Count rows in each group

To count how many observations belong to each group, use n() inside summarise():

sales_data |>
  group_by(product) |>
  summarise(number_of_transactions = n(), .groups = "drop")

For a simple frequency table, dplyr also provides count(), which is a concise alternative:

sales_data |>
  count(product, name = "number_of_transactions")

Use summarise(n = n()) when you are already building a larger summary, and use count() when the main task is simply counting rows. Continue with the dplyr count() and distinct() lesson for more examples.

7. Filter rows before grouping

You can combine filter(), group_by() and summarise() to answer more specific questions. Suppose you only want to analyse transactions with sales of at least 1,000:

sales_data |>
  filter(sales >= 1000) |>
  group_by(region) |>
  summarise(
    high_value_sales = sum(sales),
    transaction_count = n(),
    .groups = "drop"
  )

The filter is applied first, so the summary includes only transactions meeting the threshold. This is different from calculating all regional sales and then filtering the summary. Decide whether the condition applies to individual rows or to the final group-level result.

To keep only groups whose total sales exceed a threshold, summarise first and then filter:

sales_data |>
  group_by(region) |>
  summarise(total_sales = sum(sales), .groups = "drop") |>
  filter(total_sales > 3000)

8. Handle missing values correctly

Real datasets often contain missing values, represented by NA in R. Functions such as sum() and mean() return NA when their input contains missing values unless you specify how to handle them.

survey <- tibble(
  department = c("Sales", "Sales", "IT", "IT", "HR"),
  score = c(80, NA, 90, 85, NA)
)

survey |>
  group_by(department) |>
  summarise(
    average_score = mean(score, na.rm = TRUE),
    observed_scores = sum(!is.na(score)),
    missing_scores = sum(is.na(score)),
    .groups = "drop"
  )

na.rm = TRUE tells mean() to calculate the average using observed values only. The other expressions count non-missing and missing scores separately. This is safer than silently ignoring missingness, because the amount of missing data can affect how a result should be interpreted.

Important: ignoring missing values is not always appropriate. Consider why the data is missing and whether excluding those observations could bias your conclusions. Also note that sum(x, na.rm = TRUE) returns zero when all values are missing, so check the number of observed values if that distinction matters.

9. Calculate percentages and shares by group

Group summaries are often used to calculate each group's share of a total. First calculate regional sales, then divide each regional total by the overall total:

regional_sales <- sales_data |>
  group_by(region) |>
  summarise(total_sales = sum(sales), .groups = "drop")

regional_sales |>
  mutate(
    percentage_of_sales = 100 * total_sales / sum(total_sales)
  )

The denominator sum(total_sales) is calculated over the summary table, so each percentage represents that region's share of all sales represented in the data. You can round the percentage for display with round(percentage_of_sales, 1).

For a percentage within each region—for example each product's share of its region's sales—group by both variables, summarise first, and then group the summary by region to calculate the denominator within each region:

sales_data |>
  group_by(region, product) |>
  summarise(product_sales = sum(sales), .groups = "drop_last") |>
  mutate(
    region_total = sum(product_sales),
    percentage_within_region = 100 * product_sales / region_total
  ) |>
  ungroup()

Here .groups = "drop_last" drops the last grouping variable, leaving the result grouped by region. The following mutate() therefore calculates a regional denominator. If you prefer a simpler, explicit workflow, you can use .groups = "drop" and then group_by(region) again before the percentage calculation.

10. Summarise many columns with across()

When a dataset has several numeric columns, you may want the same statistics for all of them. The across() function works inside summarise() to apply a function to a selection of columns. This is an intermediate-to-advanced technique that can reduce repetitive code.

sales_data |>
  group_by(region) |>
  summarise(
    across(
      c(sales, units),
      list(total = sum, average = mean),
      .names = "{.col}_{.fn}"
    ),
    .groups = "drop"
  )

This applies both sum() and mean() to the sales and units columns in every region. The .names template creates output names such as sales_total and units_average.

If you need only totals for every numeric column, you can use where(is.numeric):

sales_data |>
  group_by(region) |>
  summarise(
    across(where(is.numeric), ~ sum(.x, na.rm = TRUE)),
    .groups = "drop"
  )

Use this pattern when all selected numeric columns can meaningfully be summed. Numeric IDs, percentages, and rates should not automatically be added together just because they are numeric.

11. Understand .groups and grouped results

The .groups argument controls the grouping structure of the result returned by summarise(). Making this explicit can prevent confusing behaviour later in a longer pipeline.

  • .groups = "drop" removes all grouping.
  • .groups = "drop_last" removes the last grouping level, which is commonly useful after grouping by multiple variables.
  • .groups = "keep" retains the grouping structure.
  • .groups = "rowwise" returns a rowwise data frame for subsequent rowwise operations.

For most beginner summaries, .groups = "drop" is a clear default because the result is a regular summary table. For multi-level analysis, choose deliberately based on what you plan to do next.

# One summary row per region-product combination;
# return an ungrouped result
sales_data |>
  group_by(region, product) |>
  summarise(total_sales = sum(sales), .groups = "drop")

Check grouping with group_vars(result) or is_grouped_df(result). Explicitly ungrouping can also make the intention clear:

summary_data <- sales_data |>
  group_by(region) |>
  summarise(total_sales = sum(sales)) |>
  ungroup()

12. Use group_by() and summarise() in a complete pipeline

In real projects, the functions are often chained together. This example filters out small transactions, groups the remaining rows by product, calculates several measures, and sorts products by total sales:

sales_data |>
  filter(sales >= 800) |>
  group_by(product) |>
  summarise(
    total_sales = sum(sales),
    average_sale = round(mean(sales), 2),
    transactions = n(),
    .groups = "drop"
  ) |>
  arrange(desc(total_sales))

The order matters. filter() chooses the transactions, group_by() defines the groups, summarise() reduces the data to one row per product, and arrange() sorts the summary. Learn more about sorting with the dplyr arrange() lesson and about filtering with dplyr filter().

13. summarise() vs mutate(): what is the difference?

These functions can both be used with grouped data, but they answer different questions.

FunctionWhat it doesTypical result
group_by()Defines groups for subsequent operationsSame rows, now grouped
summarise()Calculates a summary for each groupUsually one row per group
mutate()Adds or changes columns while preserving rowsSame number of rows

For example, use summarise() to calculate one average sale per region:

sales_data |>
  group_by(region) |>
  summarise(average_sales = mean(sales), .groups = "drop")

Use mutate() with grouping when you want each transaction to remain in the data but also want to attach its region's total:

sales_data |>
  group_by(region) |>
  mutate(region_total = sum(sales)) |>
  ungroup()

In the second example, each original transaction remains, and every row in a region receives the same regional total. See the dplyr mutate() tutorial for more detail.

14. dplyr group_by() and summarise() vs base R

You can also calculate grouped summaries using base R. For example, the following produces total sales by region:

aggregate(sales ~ region, data = sales_data, FUN = sum)

Another option is to split a vector into groups and apply a function, but aggregate() is often a concise base R equivalent for straightforward summaries. The dplyr version is convenient when you are already using pipes and want to add filtering, multiple statistics, or other data-manipulation steps.

TaskdplyrBase R
Total sales by regiongroup_by(region) |> summarise(total = sum(sales))aggregate(sales ~ region, data = sales_data, sum)
Average by regiongroup_by(region) |> summarise(avg = mean(sales))aggregate(sales ~ region, data = sales_data, mean)
Count rows by regioncount(region)as.data.frame(table(sales_data$region))

15. Common group_by() and summarise() mistakes

ProblemWhy it happensHow to fix it
Column not foundThe column name is misspelled or has different capitalisation.Check names(sales_data) and use the exact existing name.
Summary returns NAThe input contains missing values and the summary function does not remove them.Inspect missingness and, when appropriate, use na.rm = TRUE.
Only one total appearsThe data was summarised without grouping, or the grouping column is not what you expected.Check that group_by() comes before summarise().
Too many output rowsYou grouped by more variables than intended.Review the variables in group_by(); each distinct combination creates a group.
Later calculations behave unexpectedlyThe summary result may remain grouped.Use .groups = "drop" or call ungroup() explicitly.
Wrong interpretation of averageAn average transaction value is being confused with an average group total.Define the question first and choose the correct unit of analysis.

16. Practice exercises

Try each exercise using the sales_data tibble created earlier. Write the code yourself before opening the answer.

Exercise 1: Total sales by product

Calculate the total sales amount for each product.

Show answer
sales_data |>
  group_by(product) |>
  summarise(total_sales = sum(sales), .groups = "drop")

Exercise 2: Average sales and transaction count by region

Return the average sales amount and number of transactions for each region.

Show answer
sales_data |>
  group_by(region) |>
  summarise(
    average_sales = mean(sales),
    transactions = n(),
    .groups = "drop"
  )

Exercise 3: Sales by region and product

Calculate total sales for every combination of region and product.

Show answer
sales_data |>
  group_by(region, product) |>
  summarise(total_sales = sum(sales), .groups = "drop")

Exercise 4: Ignore missing values when calculating an average

Use the survey dataset from the missing-values example and calculate average score by department, excluding missing scores.

Show answer
survey |>
  group_by(department) |>
  summarise(average_score = mean(score, na.rm = TRUE), .groups = "drop")

Exercise 5: Create a percentage share

Calculate each region's share of total sales as a percentage.

Show answer
sales_data |>
  group_by(region) |>
  summarise(total_sales = sum(sales), .groups = "drop") |>
  mutate(share_percent = 100 * total_sales / sum(total_sales))

dplyr FAQ

What does group_by() do in dplyr?

group_by() marks one or more columns as grouping variables so that later dplyr operations, such as summarise(), calculate results separately for each group.

What does summarise() do in R?

summarise() reduces one or more rows to summary values, such as a total, average, count, minimum, or maximum. When the data is grouped, it calculates those values for each group.

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

group_by() defines how rows are divided into groups. summarise() calculates a result for each group. They are often used together in a pipeline.

How do I calculate totals by group in R?

Use group_by() with summarise(), for example sales |> group_by(region) |> summarise(total_sales = sum(sales), .groups = "drop").

How do I group by two columns in dplyr?

Pass both columns to group_by(), such as group_by(region, product), and summarise() will calculate a result for each region-product combination.

How do I handle missing values in summarise()?

For functions such as sum() and mean(), use na.rm = TRUE when it is appropriate to ignore missing values. Check how many values are missing before deciding how to handle them.

What does .groups = "drop" mean?

It removes grouping from the result returned by summarise(), so later operations do not continue to treat the output as grouped data.

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

summarise() usually returns fewer rows by calculating one result per group. mutate() adds or changes columns while keeping the existing rows.

Key points to remember

  • Use group_by() to define groups in a data frame.
  • Use summarise() to calculate totals, means, counts, minimums, maximums and other group-level measures.
  • Pass multiple columns to group_by() to summarise each combination.
  • Use n() to count rows in a group and across() to apply functions to multiple columns.
  • Handle missing values deliberately and use .groups = "drop" when you want an ungrouped summary.
  • Combine grouping and summaries with filter(), mutate() and arrange() to build useful analytical workflows.

Once you can group and summarise data, continue with dplyr count() and distinct() to count observations and find unique records, or review mutate() to create new variables before summarising.