typestar

across in R

Applying the same transformation to several columns at once.

library(dplyr)

runs <- tibble(
  lang = c("r", "python"),
  tpm = c(96.4, 104.2),
  accuracy = c(97.2, 99.1)
)

print(mutate(runs, across(where(is.numeric), round, 1)))

print(summarise(runs, across(c(tpm, accuracy),
                            list(mean = mean, max = max),
                            .names = "{.col}_{.fn}")))

print(mutate(runs, across(where(is.character), toupper)))
print(summarise(runs, across(everything(), ~ length(unique(.x)))))

How it works

  1. across(where(is.numeric), fn) is the common shape.
  2. A named list of functions produces one column per pair.
  3. .names controls what the new columns are called.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
394
Tokens
129
Three-star pace
95 tpm

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

Type this snippet

Step 3 of 4 in New columns, step 12 of 27 in dplyr.

← Previous Next →