user1701545
user1701545

Reputation: 6200

Collapsing data frame rows

I have a data frame, a:

> a
  GID         1          2           3          4           5          6           7          8          9          10
1   A 0.2616485 -0.1521032 -0.01281316 0.05029606 -0.01940657  0.1624178  0.14714370 0.08642461 -0.1191233 -0.01845165
2   A 0.0000000  0.0000000  0.00000000 0.00000000  0.00000000  0.0000000  0.00000000 0.00000000  0.0000000  0.00000000
3   B 0.1107565  0.1632392 -0.08760204 0.04475998 -0.10835387 -0.0827655 -0.08058794 0.15288650 -0.1120538 -0.02297707
4   B 0.0000000  0.0000000  0.00000000 0.00000000  0.00000000  0.0000000  0.00000000 0.00000000  0.0000000  0.00000000

And I'm looking for a way to get a new data frame (b) which sums the rows of data frame a by the GID column in a:

> b
  GID         1          2           3          4           5          6           7          8          9          10
1   A 0.2616485 -0.1521032 -0.01281316 0.05029606 -0.01940657  0.1624178  0.14714370 0.08642461 -0.1191233 -0.01845165
3   B 0.1107565  0.1632392 -0.08760204 0.04475998 -0.10835387 -0.0827655 -0.08058794 0.15288650 -0.1120538 -0.02297707 

Preferably using a base solution.

Upvotes: 0

Views: 1649

Answers (1)

agstudy
agstudy

Reputation: 121568

Use aggregate:

aggregate(.~GID,data=dat,sum)

EDIT

For better performance, you can try data.table:

library(data.table)
DT <- as.data.table(dat)

DT[,lapply(.SD,sum),by='GID']

Upvotes: 4

Related Questions