1

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?

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Inuraghe
  • 564
  • 3
  • 13
  • If I have other variable numeric (and I don't want sum) this code it doesn't work well, right? In this case (iris) works – Inuraghe May 09 '22 at 13:08
  • I need a function that can sum up the first four columns without writing the column name. My original dataset has 50 columns, not 4, it is a bit complicated to it for each column. – Inuraghe May 09 '22 at 13:16
  • Try `iris %>% group_by(Species) %>% summarise(across(1:4, sum))` – Darren Tsai May 09 '22 at 13:38

1 Answers1

2

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. 
Deepansh Arora
  • 724
  • 1
  • 3
  • 15