7

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?

RDavey
  • 1,530
  • 10
  • 27

1 Answers1

7

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

Johannes
  • 828
  • 12
  • 29
Bryan
  • 79
  • 1
  • 3
  • 2
    The [documentation](https://dplyr.tidyverse.org/reference/across.html#arguments) seems to indicate you do need the dot – Álvaro Mar 15 '22 at 11:22
  • 1
    I find it interesting that it works with _both_ `{.col}` (as defined) and `{col}`. Sounds like either a bug or undocumented tolerance. – r2evans Jan 13 '23 at 03:19