typestar

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

  1. slice_max(by = ...) is the per-group top n.
  2. slice_head and slice_sample take by position or at random.
  3. with_ties = FALSE keeps exactly n rows.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 5 in Rows, step 8 of 27 in dplyr.

← Previous Next →