Apply a function across a selection of columns. For use in arrange()
,
mutate()
, and summarize()
.
across(.cols = everything(), .fns = NULL, ..., .names = NULL)
vector c()
of unquoted column names. tidyselect
compatible.
Function to apply. Can be a purrr-style lambda. Can pass also list of functions.
Other arguments for the passed function
A glue specification that helps with renaming output columns.
{.col}
stands for the selected column, and {.fn}
stands for the name of the function being applied.
The default (NULL
) is equivalent to "{.col}"
for a single function case and "{.col}_{.fn}"
when a list is used for .fns
.
df <- data.table(
x = rep(1, 3),
y = rep(2, 3),
z = c("a", "a", "b")
)
df %>%
mutate(across(c(x, y), ~ .x * 2))
#> # A tidytable: 3 × 3
#> x y z
#> <dbl> <dbl> <chr>
#> 1 2 4 a
#> 2 2 4 a
#> 3 2 4 b
df %>%
summarize(across(where(is.numeric), ~ mean(.x)),
.by = z)
#> # A tidytable: 2 × 3
#> z x y
#> <chr> <dbl> <dbl>
#> 1 a 1 2
#> 2 b 1 2
df %>%
arrange(across(c(y, z)))
#> # A tidytable: 3 × 3
#> x y z
#> <dbl> <dbl> <chr>
#> 1 1 2 a
#> 2 1 2 a
#> 3 1 2 b