| across {dplyr} | R Documentation |
across() makes it easy to apply the same transformation to multiple
columns, allowing you to use select() semantics inside in summarise() and
mutate(). across() supersedes the family of "scoped variants" like
summarise_at(), summarise_if(), and summarise_all(). See
vignette("colwise") for more details.
c_across() is designed to work with rowwise() to make it easy to
perform row-wise aggregations. It has two differences from c():
It uses tidy select semantics so you can easily select multiple variables.
See vignette("rowwise") for more details.
It uses vctrs::vec_c() in order to give safer outputs.
across(.cols = everything(), .fns = NULL, ..., .names = NULL) c_across(cols = everything())
.fns |
Functions to apply to each of the selected columns. Possible values are:
Within these functions you can use |
... |
Additional arguments for the function calls in |
.names |
A glue specification that describes how to name the output
columns. This can use |
cols, .cols |
< |
A tibble with one column for each column in .cols and each function in .fns.
# across() -----------------------------------------------------------------
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), mean))
iris %>%
as_tibble() %>%
mutate(across(where(is.factor), as.character))
# A purrr-style formula
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), ~mean(.x, na.rm = TRUE)))
# A named list of functions
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), list(mean = mean, sd = sd)))
# Use the .names argument to control the output names
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), mean, .names = "mean_{.col}"))
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), list(mean = mean, sd = sd), .names = "{.col}.{.fn}"))
iris %>%
group_by(Species) %>%
summarise(across(starts_with("Sepal"), list(mean, sd), .names = "{.col}.fn{.fn}"))
# c_across() ---------------------------------------------------------------
df <- tibble(id = 1:4, w = runif(4), x = runif(4), y = runif(4), z = runif(4))
df %>%
rowwise() %>%
mutate(
sum = sum(c_across(w:z)),
sd = sd(c_across(w:z))
)