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
- Every verb after
group_byworks within the groups. summarizepeels one grouping level off.ungroupbefore returning, or the caller inherits the grouping.
Keywords and builtins used here
cgroup_bygroup_varslibrarymeanmutateprintroundsumsummarisetibbleungroup
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.
Step 1 of 4 in Grouping, step 14 of 27 in dplyr.