Across with multiple arguments

Viewed 34

This can be a very dumb question regarding application of 'across' function with multiple columns and different funs applied to each. For eg, below is an example from 'iris' data where column names starting with 'Sepal' are averaged. What if I along with this I want to take median of columns starting with 'Petal'. How can I give the two different column types and funs in same summarise?

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean))
1 Answers

You can add multiple across statements in one summarise/mutate :

library(dplyr)

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), mean), 
            across(starts_with("Petal"), median))

#  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
#* <fct>             <dbl>       <dbl>        <dbl>       <dbl>
#1 setosa             5.01        3.43         1.5          0.2
#2 versicolor         5.94        2.77         4.35         1.3
#3 virginica          6.59        2.97         5.55         2  
Related