group_by and summarize in R
The split-apply-combine heart of dplyr.
library(dplyr)
by_cyl <- mtcars %>%
group_by(cyl) %>%
summarise(
n = n(),
avg_mpg = mean(mpg),
sd_mpg = sd(mpg),
best = max(mpg),
.groups = "drop"
) %>%
arrange(desc(avg_mpg))
two_way <- mtcars %>%
group_by(cyl, am) %>%
summarise(avg = mean(mpg), .groups = "drop")
How it works
group_bysets the grouping columns.summarizecollapses each group to one row.n()counts rows;.groups = "drop"ungroups after.
Keywords and builtins used here
arrangedescgroup_bylibrarymaxmeannsdsummarise
The run, in numbers
- Lines
- 16
- Characters to type
- 266
- Tokens
- 80
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 48 seconds.
Step 4 of 4 in Grouping, step 17 of 27 in dplyr.