01 / 20

group_by() &
summarize()

Learn how to split data into groups and compute summary statistics using the tidyverse's most powerful data-wrangling verbs.

R Programming

What Is Grouping Data?

Imagine you have a table of student test scores. You want to know the average score per class, not just the overall average. Grouping means splitting your data into subsets based on a shared column value, so you can analyze each subset independently.

The Split-Apply-Combine Pattern

Original Data class A, 85 class B, 92 class A, 78 class B, 88 class A, 90 SPLIT Group A 85 78 90 Group B 92 88 APPLY mean: 84.3 mean: 90 COMBINE Result A: 84.3 B: 90.0

Why Group & Summarize Matters

Efficiency
One line of code replaces dozens of manual calculations across categories.
Clarity
Code reads like English: "group by species, then summarize the mean weight."
Scalability
Works the same whether you have 10 rows or 10 million rows.

Nearly every data analysis task involves computing statistics per group: average sales per region, max temperature per city, total votes per candidate. This is where group_by() and summarize() become essential.

The Core Syntax

result <- data %>% group_by(column_name) %>% summarize( new_col = summary_function(column) )
1
group_by(column): tells R which column defines the groups.
2
summarize(new = func(col)): computes a summary stat for each group and returns one row per group.

Common Summary Functions

Function What It Computes Example
mean() Average (arithmetic mean) mean(score)
median() Middle value median(score)
sum() Total of all values sum(sales)
n() Count of rows in each group n()
sd() Standard deviation sd(weight)
min() / max() Smallest / largest value max(temp)

group_by() vs. summarize() Alone

summarize() alone
Without group_by(), summarize() collapses the entire data frame into a single row: one overall summary.
group_by() + summarize()
With group_by() first, summarize() produces one row per group: separate summaries for each category.
# Overall mean (1 row) students %>% summarize(avg = mean(score)) # Mean per class (1 row per class) students %>% group_by(class) %>% summarize(avg = mean(score))

Step-by-Step Workflow

1
Load tidyverse: library(tidyverse) or library(dplyr)
2
Inspect your data: use glimpse(data) or head(data) to see column names and types.
3
Identify the grouping column: which categorical variable defines your groups?
4
Choose your summary function(s): mean(), sum(), n(), etc.
5
Write the pipeline: data %>% group_by(col) %>% summarize(stat = func(col))

Example 1: Average Score by Class

library(dplyr) students <- tibble( name = c("Ana", "Ben", "Cara", "Dan", "Eva"), class = c("A", "B", "A", "B", "A"), score = c(85, 92, 78, 88, 90) ) students %>% group_by(class) %>% summarize(avg_score = mean(score))

Example 2: Multiple Summaries

students %>% group_by(class) %>% summarize( avg_score = mean(score), max_score = max(score), num_students = n() )
class avg_score max_score num_students A 84.3 90 3 B 90.0 92 2

Example 3: Combining with filter()

You can chain filter(), group_by(), and summarize() together. The pipe operator lets you build a pipeline that reads top to bottom.

students %>% filter(score >= 80) %>% group_by(class) %>% summarize( high_avg = mean(score), count = n() )

The n() Function

n() is special: it takes no arguments and returns the number of rows in each group. It only works inside summarize() (or mutate() with a grouped data frame).

# Count students per class students %>% group_by(class) %>% summarize(count = n())

Grouping by Multiple Columns

You can group by more than one column. R creates a unique group for every combination of values in those columns.

sales %>% group_by(region, quarter) %>% summarize( total_sales = sum(revenue), avg_order = mean(order_size) )

Don't Forget ungroup()

After summarize() with multiple grouping columns, the result may still be grouped by the first column. This can cause unexpected behavior in later operations. Always ungroup() when you're done.

sales %>% group_by(region, quarter) %>% summarize(total = sum(revenue)) %>% ungroup()

Common Mistakes

✕ Forgetting group_by()
Using summarize() without group_by() gives you a single overall result instead of per-group summaries.
✕ Wrong column in group_by()
Grouping by a numeric column (like score) instead of a categorical one creates a group for every unique number.
✕ Using = instead of ==
Inside filter(), use == for comparison. Inside summarize(), use = for naming columns. Mixing them up causes errors.

Quick Reference Cheat Sheet

Task Code Pattern Output Rows
Overall summary summarize(stat = func(col)) 1
Per-group summary group_by(g) %>% summarize(...) 1 per group
Multi-group summary group_by(g1, g2) %>% summarize(...) 1 per combo
Count per group group_by(g) %>% summarize(n = n()) 1 per group
Filter then summarize filter(...) %>% group_by(g) %>% summarize(...) 1 per group

Question 1 of 5

What does group_by() do to a data frame?

Question 2 of 5

Given this code, how many rows will the output have?

df %>% group_by(color) %>% summarize(avg = mean(price))

df has 100 rows and the color column has 4 unique values: red, blue, green, yellow.

Question 3 of 5

Which function counts the number of rows in each group?

Question 4 of 5

What happens if you call summarize(avg = mean(score)) without group_by() first?

Question 5 of 5

Which code correctly computes the total sales and number of orders per region?