group_by and summarise (dplyr) (R)
group_by splits a data frame into groups by one or more columns, and summarise collapses each group to summary statistics. Together they perform grouped aggregation — the split-apply-combine pattern.
R
group_by(df, category) tags a data frame with grouping, changing nothing on its own but making subsequent verbs operate per group. summarise() (or summarize()) then reduces each group to a single row of computed statistics: counts, means, sums, etc. The result has one row per group.
This is dplyr's expression of split-apply-combine: split the data by group, apply an aggregation, and combine the results into a tidy table. df %>% group_by(species) %>% summarise(avg = mean(weight), n = n()) gives the average weight and count for each species.
You can group by multiple columns for cross-tabulated summaries, and group_by also affects mutate (computing within each group) and filter. Remember that summarise removes one level of grouping; use ungroup() to clear grouping afterward when needed.
Syntax
df %>% group_by(category) %>% summarise(avg = mean(value), n = n())Examples
R — Produces one row per cylinder count with the mean mpg and group size.
library(dplyr)
mtcars %>%
group_by(cyl) %>%
summarise(
avg_mpg = mean(mpg),
count = n()
)