0Pricing
R Academy · Lesson

Grouped Summaries and group_by()

Aggregate data by groups and compute per-group statistics.

Why Group Data?

Grouping data is one of the most powerful operations in data analysis. Instead of computing statistics over an entire dataset, you compute them within each group. The dplyr package makes this intuitive with group_by() followed by summarize().

library(dplyr)

# Sample sales data
sales <- data.frame(
  region = c('North','North','South','South','East'),
  revenue = c(120, 95, 200, 175, 88),
  units = c(10, 8, 15, 12, 7)
)

print(sales)

group_by() Basics

group_by(col) marks a data frame so that subsequent operations happen per group. It does not change the data itself — it adds grouping metadata. You can group by one or multiple columns.

library(dplyr)

sales <- data.frame(
  region = c('North','North','South','South','East'),
  revenue = c(120, 95, 200, 175, 88),
  units = c(10, 8, 15, 12, 7)
)

# Group by region
grouped <- sales %>% group_by(region)
print(grouped)
print(group_keys(grouped))

All lessons in this course

  1. Grouped Summaries and group_by()
  2. Window Functions: lag, lead, cumsum
  3. Multi-table Joins in dplyr
  4. Tidy Evaluation: {{ }} and .data
← Back to R Academy