typestar

group_by in R

Grouping persists until you ungroup, which is the usual source of bugs.

library(dplyr)

runs <- tibble(
  lang = c("r", "r", "python", "python"),
  day = c("mon", "tue", "mon", "tue"),
  tpm = c(88, 96, 104, 99)
)

grouped <- group_by(runs, lang)
print(group_vars(grouped))
print(mutate(grouped, share = round(tpm / sum(tpm), 3)))

summary <- summarise(group_by(runs, lang, day), tpm = mean(tpm),
                     .groups = "drop_last")
print(group_vars(summary))
print(ungroup(summary))

How it works

  1. Every verb after group_by works within the groups.
  2. summarize peels one grouping level off.
  3. ungroup before returning, or the caller inherits the grouping.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
392
Tokens
130
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 1 of 4 in Grouping, step 14 of 27 in dplyr.

← Previous Next →