carvalhosantos
carvalhosantos

Reputation: 57

how to sum several columns in r?

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.

Upvotes: 2

Views: 635

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101034

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)

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use base R

sapply(iris[1:4], sum)

Upvotes: 2

M.Viking
M.Viking

Reputation: 5398

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))

Upvotes: 4

Related Questions