dufei
dufei

Reputation: 3357

How to glue a function argument to .names in dplyr's across function?

I am trying to name the output of an across function using both {col} and one of the function arguments in

library(tidyverse)

mean_by <- function(data, by, var, prefix = "avg") {
  data %>% 
    group_by({{ by }}) %>% 
    summarise(across({{ var }}, mean, .names = "{prefix}_{col}"))
}

However, when testing on iris %>% mean_by(Species, Sepal.Width), I get the error that object 'prefix' cannot be found. The glue syntax in .names looks okay to me so I assume this is a scoping issue? Can the .names argument only access what has been passed to across?

Upvotes: 2

Views: 719

Answers (1)

iago
iago

Reputation: 3256

I believe .names in across only allow references to {col} and {fn} inside across, but you can try pasting your prefix:

> library(tidyverse)
> mean_by <- function(data, by, var, prefix = "avg") {
  data %>% 
    group_by({{ by }}) %>% 
    summarise(across({{ var }}, mean, .names = paste0(prefix,"_{col}")))
 }
> iris %>% mean_by(Species, Sepal.Width)
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 2
  Species    avg_Sepal.Width
  <fct>                <dbl>
1 setosa                3.43
2 versicolor            2.77
3 virginica             2.97

Upvotes: 3

Related Questions