3

I have seen this (Summarize different Columns with different Functions)

But in my situation, I want to use sum() with mpg, disp and hp. And use mean() with drat, wt and qsec.

All the function should be used with a group variable cyl.

Like this:

result.1 = mtcars %>% group_by(cyl) %>% summarise(across(.cols = c(mpg, disp, hp),
                                              .fns = sum))


result.2 = mtcars %>% group_by(cyl) %>% summarise(across(.cols = c(drat:qsec),
                                              .fns = mean))

final.result = full_join(result.1, result.2)

Is this possible that get final.result only use summarise() once.

Any help will be highly appreciated!

M--
  • 25,431
  • 8
  • 61
  • 93
zhiwei li
  • 1,635
  • 8
  • 26

1 Answers1

2

You can use across twice in the same summarise call :

library(dplyr)

mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(.cols = c(mpg, disp, hp),.fns = sum), 
            across(.cols = c(drat:qsec),.fns = mean))

#    cyl   mpg  disp    hp  drat    wt  qsec
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     4  293. 1156.   909  4.07  2.29  19.1
#2     6  138. 1283.   856  3.59  3.12  18.0
#3     8  211. 4943.  2929  3.23  4.00  16.8
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213