group_by() &
summarize()
Learn how to split data into groups and compute summary statistics using the tidyverse's most powerful data-wrangling verbs.
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
Why Group & Summarize Matters
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
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
Step-by-Step Workflow
Example 1: Average Score by Class
Example 2: Multiple Summaries
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.
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).
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.
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.
Common Mistakes
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 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?