'Group by or sum more column [duplicate]

I would like to know if exist a method "automatic" for calculted more column in the same time.

library(dplyr)
abc <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Petal.Width)) %>% 
      ungroup() 
abc2 <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Sepal.Width)) %>% 
      ungroup() 

I can use this code for each column but if i need to do more column (in this dataset the first four), how can I do? And I need in the same dataset, it is possible?



Solution 1:[1]

Try this:

iris %>% 
  group_by(Species) %>% 
  summarise(across(Sepal.Length:Petal.Width, sum))


# A tibble: 3 x 5
  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa             250.        171.         73.1        12.3
2 versicolor         297.        138.        213          66.3
3 virginica          329.        149.        278.        101. 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deepansh Arora