Add values ​​in data frame cells based on condition

I have a table that looks like this:

ID    c1    c2    c3    c4
A     23    12    45    63
A     3     1     6     17
B     3     1     4     6
B     2     2     5     3

and I would like to get something like this,

ID    c1    c2    c3    c4
A     26    13    51    80
B     5     3     9     9

where each cell is the sum of the values ​​that are mapped to the same identifier.

I would like to solve this with R. Any thoughts? I know that if they want to sum all the values ​​in a column, I can use colsums, but I'm not sure how to sum the values ​​based on the criteria.

Any help would be appreciated.

Frame

PS: the actual table, I have 45000 rows and 72 columns.

+3
source share
3 answers

Try

aggregate( . ~ ID, data = x, FUN = sum)

  ID c1 c2 c3 c4
1  A 26 13 51 80
2  B  5  3  9  9
+3
source

Another way with plyr

library(plyr)
ddply(x, .(ID), numcolwise(sum))

  ID c1 c2 c3 c4
1  A 26 13 51 80
2  B  5  3  9  9
+2
source

For a faster alternative:

library(data.table)
dt = data.table(df)

dt[, lapply(.SD, sum), by = ID]
#   ID c1 c2 c3 c4
#1:  A 26 13 51 80
#2:  B  5  3  9  9
+2
source

All Articles