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