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
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)))