how do I search for columns with same name, add the column values and replace these columns with same name by their sum? Using R

后端 未结 4 660
情话喂你
情话喂你 2021-01-05 20:56

I have a data frame where some consecutive columns have the same name. I need to search for these, add their values in for each row, drop one column and replace the other wi

4条回答
  •  梦毁少年i
    2021-01-05 21:27

    One way is to identify duplcates using (surprise) the duplicated function, and then loop through them to calculate the sums. Here is an example:

    dat.dup <- data.frame(x=1:10, x=1:10, x=1:10, y=1:10, y=1:10, z=1:10, check.names=FALSE)
    dups <- unique(names(dat.dup)[duplicated(names(dat.dup))])
    for (i in dups) {
    dat.dup[[i]] <- rowSums(dat.dup[names(dat.dup) == i])
    }
    dat <- dat.dup[!duplicated(names(dat.dup))]
    

提交回复
热议问题