Learn R Programming

poorman (version 0.2.3)

across: Apply a function (or functions) across multiple columns

Description

across() makes it easy to apply the same transformation to multiple columns, allowing you to use select() semantics inside in "data-masking" functions like summarise() and mutate().

across() supersedes the family of dplyr "scoped variants" like summarise_at(), summarise_if(), and summarise_all() and therefore these functions will not be implemented in poorman.

Usage

across(.cols = everything(), .fns = NULL, ..., .names = NULL)

Arguments

.fns

Functions to apply to each of the selected columns. Possible values are:

  • NULL, to returns the columns untransformed.

  • A function, e.g. mean.

  • A list of functions, e.g. list(mean = mean, sum = sum)

Within these functions you can use cur_group() to access the current grouping keys.

...

Additional arguments for the function calls in .fns.

.names

character(n). Currently limited to specifying a vector of names to use for the outputs.

cols, .cols

<poor-select> Columns to transform. Because across() is used within functions like summarise() and mutate(), you can't select or compute upon grouping variables.

Value

A data.frame with one column for each column in .cols and each function in .fns.

Examples

Run this code
# NOT RUN {
# across() -----------------------------------------------------------------
iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean))
iris %>%
  mutate(across(where(is.factor), as.character))

# Additional parameters can be passed to functions
iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean, 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 = c("mean_sepal_length", "mean_sepal_width"))
  )

# }

Run the code above in your browser using DataLab