Learn tidyverse Β· 4/13

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. πŸ€–

r
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).

r
# Calculate the average height of ALL characters
starwars %>%
  summarize(
    avg_height = mean(height, na.rm = TRUE),
    total_characters = n()
  )

Output:

text
# 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 run mean() 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.

r
# 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):

text
# 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.

r
# 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.

r
# Who are the most common species?
starwars %>%
  count(species, sort = TRUE) 

Output:

text
# 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.

r
# 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.

r
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.

r
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.

  1. Summarize: Principal asks, "What is the school's average GPA?" (Collapses school to 1 number).
  2. Group By + Summarize: Principal asks, "What is the average GPA per class?" (Collapses school to 12 numbers, one per grade level).
  3. 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 βœ…

  1. summarize(): Shrinks data. Use for reporting stats.
  2. group_by(): splits data. Always pair with summarize/mutate.
  3. ungroup(): The safety switch. Always use it after grouping.
  4. count(): The shortcut for frequency tables.
  5. Window Functions: group_by + mutate/filter lets you compare individuals against their group.

πŸ“š References & Further Reading

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:

  1. Groups the data by the homeworld variable.
  2. Calculates the average height for each homeworld. Be sure to handle missing values in the height column appropriately.
  3. For each character, calculates the absolute difference between their individual height and their homeworld's average height.
  4. Filters the data to keep only the character (or characters, in case of a tie) with the smallest height difference for each homeworld.
  5. Selects the following columns in the final output: name, homeworld, height, the calculated average homeworld height, and the calculated height difference.
  6. 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):

tap
# 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
...
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.