Reputation: 625
I'd like to combine multiple columns of a data frame in R. Given data that look something like this:
names: 123 256 192 123 256
1 2 8 2 3
4 3 2 9 9
8 7 1 3 8
How would I sum the elements of the identically-named columns to produce a table like so:
names: 123 256 192
3 5 8
13 12 2
11 15 1
Thank you very much.
Upvotes: 5
Views: 8953
Reputation: 57220
As suggested by @VincentZoonekynd it is not a good idea to have multiple columns with the same name.
Anyway, you could do in this way:
df <- data.frame(A=c(1,4,8),B=c(2,3,7),C=c(8,2,1),D=c(2,9,3),E=c(3,9,8))
names(df) <- c('123','256', '192', '123', '256')
df <- t(df) # transpose the data.frame
aggr <- by(df, INDICES=row.names(df), FUN=colSums) # collapse the rows with the same name
aggr <- as.data.frame(do.call(cbind,aggr)) # convert by() result to a data.frame
or, in one line:
aggr <- as.data.frame(do.call(cbind, by(t(df),INDICES=names(df),FUN=colSums)))
Upvotes: 6