Picking rows per group in R
The top row per group, and the other slice variants.
library(dplyr)
runs <- tibble(
lang = c("r", "r", "python", "python", "python"),
day = c(1, 2, 1, 2, 3),
tpm = c(88, 96, 104, 99, 104)
)
print(slice_max(runs, tpm, n = 1, by = lang))
print(slice_max(runs, tpm, n = 1, by = lang, with_ties = FALSE))
print(slice_head(runs, n = 1, by = lang))
set.seed(1)
print(slice_sample(runs, n = 2))
print(slice(runs, 2:3))
How it works
slice_max(by = ...)is the per-group top n.slice_headandslice_sampletake by position or at random.with_ties = FALSEkeeps exactly n rows.
Keywords and builtins used here
clibraryprintsliceslice_headslice_maxslice_sampletibble
The run, in numbers
- Lines
- 14
- Characters to type
- 360
- Tokens
- 137
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 87 seconds.
Step 4 of 5 in Rows, step 8 of 27 in dplyr.