0

I have this df

df<-data.frame(category=c("food","clothes","clothes","food"),item=c("bread","shirt","shoes","fish"),number=c(2,5,8,3))

and I need to sum the value of the items in the greater sets of "food" and "clothes" in order to get a table like the following.

tot<-data.frame(category=c("food","clothes"),number=c(5,13))

How can I do it?

Thank you

2 Answers2

0

If you do not mind using package dplyr:

library(dplyr)
tot <- df %>% group_by(category) %>% summarise(number = sum(number))

Output:

> tot
# A tibble: 2 x 2
  category number
  <chr>     <dbl>
1 clothes      13
2 food          5
Paul
  • 2,850
  • 1
  • 12
  • 37
0

Try a base R option with aggregate

> aggregate(number ~ category, df, sum)
  category number
1  clothes     13
2     food      5
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81