typestar

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

  1. group_by sets the grouping columns.
  2. summarize collapses each group to one row.
  3. n() counts rows; .groups = "drop" ungroups after.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Grouping, step 17 of 27 in dplyr.

← Previous Next →