Aggregation and Grouping (dplyr Summaries)
6 min read
Welcome back to the tidyverse! π
If the previous modules were about cleaning your room (selecting and filtering), this module is about asking: "Okay, I have all this stuff... now, what does it all mean?"
Imagine you are looking at a spreadsheet with 50,000 rows of sales data. Your boss walks in, spills coffee on your desk, and asks, "What's the average sale per region?" You cannot simply hand them the 50,000 rows. You need to crush that data down into a single, digestible number.
That is Aggregation.
In this guide, we will master the art of the "Split-Apply-Combine" strategy using dplyr. This is the bread and butter of data analysis.
Prerequisites
Make sure you have the tidyverse loaded. We will use the built-in starwars dataset for our examples because, frankly, analyzing galactic demographics is way more fun than analyzing iris flowers. π€
library(tidyverse)
# Let's peek at our data
glimpse(starwars)1. summarize(): Condensing Data into Meaningful Metrics
The Concept
Definition: summarize() (or summarise()βR speaks both US and UK English) takes a data frame and creates a new data frame with one or more rows depending on the grouping, calculating summary statistics for specific columns.
The Problem
You have a column of numbers (like heights). You don't want the list of heights; you want the average height. You need to reduce n observations to 1 value.
The Solution
We use summarize() alongside aggregate functions like mean(), median(), sum(), sd() (standard deviation), or n() (count).
# Calculate the average height of ALL characters
starwars %>%
summarize(
avg_height = mean(height, na.rm = TRUE),
total_characters = n()
)Output:
# A tibble: 1 Γ 2
avg_height total_characters
<dbl> <int>
1 174. 87π§ Industry Standard: The NA Trap
You noticed na.rm = TRUE, didn't you?
In R, NA stands for "Not Available." If you try to calculate the mean of 10, 20, NA, R says, "I don't know the third number, so I don't know the average," and returns NA.
Always consider handling missing values explicitly in your summaries.
Useful Summary Functions:
mean(x): Average.median(x): Median (robust to outliers).sum(x): Total.min(x)/max(x): Range.n(): Current group size (number of rows).n_distinct(x): Number of unique values.
Did you know? π€―
If you runmean()on a logical vector (TRUE/FALSE), it gives you the proportion of TRUEs!mean(c(TRUE, TRUE, FALSE))= 0.66 (66%). This is a super quick way to find percentages.
2. group_by(): The Real Power of Grouped Operations
The Concept
Definition: group_by() takes an existing data frame and converts it into a grouped data frame where operations are performed "by group".
The Problem
summarize() is great, but it collapses the entire dataset into one row.
What if your boss asks, "What is the average height per species?"
You could filter for Droids, summarize, then filter for Humans, summarize... but that would take forever and is prone to errors.
The Solution: Split-Apply-Combine
We use group_by() to split the data silently. When we pass this grouped data to summarize(), it automatically calculates the stats for each group and then combines them back together.
# Average height and mass PER Species
species_summary <- starwars %>%
group_by(species) %>%
summarize(
avg_height = mean(height, na.rm = TRUE),
avg_mass = mean(mass, na.rm = TRUE),
count = n()
)
head(species_summary)Output (Preview):
# A tibble: 6 Γ 4
species avg_height avg_mass count
<chr> <dbl> <dbl> <int>
1 Aleena 79 15 1
2 Besalisk 198 102 1
3 Cerean 198 82 1
...π Crucial Industry Practice: The ungroup() Rule
When you use group_by(), R adds invisible metadata to your dataframe saying "I am grouped."
If you continue working on this object later, filters and mutates will still happen per group, which can lead to disastrous performance or logic bugs.
The Golden Rule: Always ungroup() when you are done with your grouped operation.
# Safe practice
clean_summary <- starwars %>%
group_by(species) %>%
summarize(avg_height = mean(height, na.rm = TRUE)) %>%
ungroup() # π Free the data!Under the hood:
group_by()doesn't actually shuffle the rows of your data. It generates an internal index of which rows belong to which group. It's very memory efficient!
3. Counting and Tallying: Quick Frequencies (count())
The Concept
Definition: count() is a wrapper function that groups by a variable, counts the occurrences, and (optionally) sorts them.
The Problem
Finding the frequency of categories is the most common task in data analysis.
Writing group_by(x) %>% summarize(n = n()) is 34 characters. Programmers are lazy. We want to type less.
The Solution
Use count(). It does the exact same thing but faster.
# Who are the most common species?
starwars %>%
count(species, sort = TRUE) Output:
# A tibble: 38 Γ 2
species n
<chr> <int>
1 Human 35
2 Droid 6
3 NA 4
...Pro Tip: You can count by multiple variables to get a cross-tabulation.
# Count breakdown by Sex and Gender
starwars %>%
count(sex, gender, sort = TRUE)4. Grouped Mutates and Filters: Window Functions
The Concept
Definition: Window functions take an input vector of size n and return an output vector of size n.
The Problem
summarize() destroys your rows. It collapses 87 Star Wars characters into 38 Species rows.
But what if you want to answer: "Which characters are taller than the average for their own species?"
To answer this, you need the original character row and the group average in the same context.
The Solution
Use group_by() followed by mutate() or filter(). This calculates the aggregate (like mean) but keeps all original rows.
Scenario A: The "Grouped Mutate"
Add a column showing the average height of the species the character belongs to.
starwars_expanded <- starwars %>%
select(name, species, height) %>% # Selecting few cols for clarity
group_by(species) %>%
mutate(
species_avg_height = mean(height, na.rm = TRUE),
diff_from_avg = height - species_avg_height
) %>%
ungroup()
head(starwars_expanded)What happened here?
If you look at the Human rows, species_avg_height will be identical for all humans. R calculated the mean for humans and "pasted" it into every human row.
Scenario B: The "Grouped Filter"
Keep only the tallest member of each species.
tallest_per_species <- starwars %>%
select(name, species, height) %>%
group_by(species) %>%
filter(height == max(height, na.rm = TRUE)) %>%
ungroup()
# Now you see who represents the peak physical performance of their kind
head(tallest_per_species)Real Life Simulation: The "Classroom Grade" Scenario π«
Imagine a school database.
- Summarize: Principal asks, "What is the school's average GPA?" (Collapses school to 1 number).
- Group By + Summarize: Principal asks, "What is the average GPA per class?" (Collapses school to 12 numbers, one per grade level).
- Group By + Mutate: A student asks, "Did I score higher than the average of my class?" (Keeps all students, adds a column comparing them to their peers).
Summary Checklist β
summarize(): Shrinks data. Use for reporting stats.group_by(): splits data. Always pair with summarize/mutate.ungroup(): The safety switch. Always use it after grouping.count(): The shortcut for frequency tables.- Window Functions:
group_by+mutate/filterlets you compare individuals against their group.
π References & Further Reading
- Official dplyr documentation (Summarise)
- Official dplyr documentation (Group By)
- R for Data Science: Data Transformation
- The Split-Apply-Combine Strategy (Paper by Hadley Wickham)
Happy Coding! π
Challenge
Challenge: The Most 'Average' Inhabitant
Using the starwars dataset, perform an analysis to find the character from each homeworld whose height is the closest to the average height of all inhabitants from that same world. This is a common task in data analysis, used to find representatives or outliers within subgroups.
Your task is to write a dplyr pipeline that:
- Groups the data by the
homeworldvariable. - Calculates the average height for each homeworld. Be sure to handle missing values in the
heightcolumn appropriately. - For each character, calculates the absolute difference between their individual height and their homeworld's average height.
- Filters the data to keep only the character (or characters, in case of a tie) with the smallest height difference for each homeworld.
- Selects the following columns in the final output:
name,homeworld,height, the calculated average homeworld height, and the calculated height difference. - Removes the grouping from the final tibble.
Expected result
Your code should produce a tibble where each row represents the character from a specific homeworld who is closest in height to the average for that world.
The final output should contain exactly five columns in the specified order:
name: The character's name.homeworld: The character's homeworld.height: The character's height.- A column containing the calculated average height for that homeworld.
- A column containing the calculated absolute difference between the character's height and the homeworld's average.
For example, the first few rows of your result should look similar to this (the exact row order and column names for calculated fields may vary):
# A tibble: 38 Γ 5
name homeworld height homeworld_avg_height height_diff
<chr> <chr> <int> <dbl> <dbl>
1 Leia Organa Alderaan 150 177. 26.7
2 Bossk Trandosha 190 190 0
3 Chewbacca Kashyyyk 228 228 0
4 Mon Mothma Chandrila 150 150 0
5 Dexter Jettster Ojom 198 198 0
6 Lama Su Kamino 229 221. 8
7 R2-D2 Naboo 96 149. 53.3
8 Beru Whitesun lars Tatooine 165 174. 9.44
...