Search code examples
rdplyracross

How to use function's name in across() when combining functions?


When I try to use the across() function with many functions to be applied, as a result I get columns named as can be seen below:

iris %>% summarise(across(Petal.Length, .fns = c(mean, median, var, sd), .names = "{fn}_{col}")

  1_Petal.Length 2_Petal.Length 3_Petal.Length 4_Petal.Length
1          3.758           4.35       3.116278       1.765298

The columns' names are 1_Petal.Length, 2_Petal.Length etc., but what I want to get are functions' names instead of the numbers, e.g. mean_Petal.Length, median_Petal.Length etc. just as when there's only one function in the .fns argument. I know I can name the functions with .fns = c(mean=mean, median=median, var=var, sd=sd), but is there any easier way which I'm missing here?


Solution

  • You can use lst instead of c :

    library(dplyr)
    
    iris %>% summarise(across(Petal.Length, 
                      .fns = lst(mean, median, var, sd), 
                      .names = "{fn}_{col}"))
    
    #  mean_Petal.Length median_Petal.Length var_Petal.Length sd_Petal.Length
    #1             3.758                4.35         3.116278        1.765298
    

    lst creates a named arguments automatically without specifying them manually like c(mean=mean...).