Combining Multiple Identically-Named Columns in R

前端 未结 1 1162
-上瘾入骨i
-上瘾入骨i 2021-01-06 10:24

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         


        
相关标签:
1条回答
  • 2021-01-06 11:06

    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)))
    
    0 讨论(0)
提交回复
热议问题