nouse
nouse

Reputation: 3471

Summing up rows in a dataframe by a common factor

I hope this hasnt been asked too many times. Here is example data:

structure(list(Cluster = c(1L, 1L, 1L, 1L, 5L, 5L, 5L, 13L, 17L, 
26L, 26L, 26L, 26L, 26L), X1 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 
0L, 0L, 30L, 24L, 129L, 50L, 1L), X2 = c(0L, 0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 3L, 39L, 111L, 37L, 0L), X3 = c(0L, 0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 74L, 80L, 15L, 40L, 0L), X4 = c(0L, 0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 68L, 90L, 10L, 11L, 0L), X5 = c(0L, 0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 17L, 17L, 53L, 28L, 0L), X6 = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 112L, 31L, 85L, 85L, 0L), X7 = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 82L, 211L, 91L, 28L, 0L), X8 = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 8L, 10L, 111L, 41L, 0L), X9 = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 111L, 57L, 17L, 22L, 0L)), .Names = c("Cluster", 
"X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "X9"), class = "data.frame", row.names = c("Wn0Sey25", 
"AewYy021", "HewYy267", "Wn0Sey16", "Wn0Se169", "EU861874.1.1466", 
"Wn0Sey03", "HQ178918.1.1424", "FR774764.1.1456", "Wm2Ae125", 
"Wm2Ae171", "HQ729797.1.1480", "HewYy246", "AewYyy56"))

I want to sum up rows with the same value in the field "cluster". I dont care what happens to the row IDs.

Thank you very much!

Upvotes: 0

Views: 128

Answers (1)

akrun
akrun

Reputation: 887621

You can try

library(dplyr)
df1 %>% 
     group_by(Cluster) %>% 
     summarise_each(funs(sum))

Upvotes: 2

Related Questions