how to sum several columns in r?

Viewed 98

I would like sum several columns in my dataframe. For exemple, using iris r-base

I would like, for example, to sum the columns Sepal.Length, Petal.Length, and Petal.Width

I tried colSums, but it did not work.

 df<-iris%>%
  select(-Species)%>%
  colSums([1:4])

Update: I tried to modify the question closer to my reality.

3 Answers

I think you want to do

colSums(iris[1:4])

or

iris[1:4] %>% colSums()

Other options with the %>% pipe are

iris %>% 
  select(Sepal.Length,  Sepal.Width, Petal.Length,  Petal.Width) %>% 
  colSums()

or using the new across function

iris %>% 
  summarise(across(1:4, sum))

The more verbose option, but i like to use this when adding min, max quartile, etc

iris %>% 
  summarise(Sepal.Length = sum(Sepal.Length),  
            Sepal.Width  = sum(Sepal.Width), 
            Petal.Length = sum(Petal.Length),  
            Petal.Width  = sum(Petal.Width))

We can use base R

sapply(iris[1:4], sum)

Here is another base R trick with aggregate

> aggregate(. ~ is.na(Species), iris, sum)[-1]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1        876.5       458.6        563.7       179.9     300

or (thank @akrun for comments)

aggregate(. ~ Species, transform(iris, Species = 1), sum)
Related