RDavey
RDavey

Reputation: 1909

How to use .names with dplyr mutate across and an anonymous function

Referring to the documentation for across() (https://dplyr.tidyverse.org/reference/across.html), you can specify the name returned from the dplyr verb using the .names argument. Viz

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean, .names = "mean_{.col}"))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 3 x 3
#>   Species    mean_Sepal.Length mean_Sepal.Width
#>   <fct>                  <dbl>            <dbl>
#> 1 setosa                  5.01             3.43
#> 2 versicolor              5.94             2.77
#> 3 virginica               6.59             2.97

However, when I use a purr style anonymous function I receive an error:

iris %>% 
   group_by(Species) %>%
   mutate(across(contains(".Width"), ~.x - mean(.x), .names = "residual_{.col}"))

#> Error: Problem with `mutate()` input `..1`.
#> x glue cannot interpolate functions into strings.
#> * object '.col' is a function.
#> i Input `..1` is `across(contains(".Width"), ~.x - mean(.x), .names = "residual_{.col}")`.
#> i The error occured in group 1: Species = "setosa".
#> Run `rlang::last_error()` to see where the error occurred.

Removing the .names argument removes the error. How is one supposed to specify names using across in a dplyr verb with an anonymous function?

Upvotes: 10

Views: 8744

Answers (1)

Bryan
Bryan

Reputation: 109

Try removing the dot in .col, so it will be: .names = "residual_{col}"

Upvotes: 10

Related Questions