Вот еще одна базовая R-альтернатива.Я думаю, что ответ Руи Баррадеса, вероятно, лучше, но может быть полезно увидеть несколько подходов.
# save column names
cnms <- colnames(myMat)
# build a matrix that groups on column names using col and grepl
grps <- col(diag(length(cnms))) * sapply(cnms[order(cnms)], grepl, x=cnms)
# run through the groups and perform rowSums to collapse groups into one column
sapply(split(seq_len(ncol(myMat)),
colnames(grps)[apply(grps, 1, FUN=function(x) min(x[x != 0]))]),
function(y) rowSums(myMat[, y]))
Это возвращает
Chips Ketchup
[1,] 1 1
[2,] 0 1
[3,] 1 0
[4,] 0 1
data
myMat <-
structure(c(0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 0L, 1L, 0L, 0L, 0L), .Dim = 4:5, .Dimnames = list(NULL,
c("Ketchup", "Ketchupwithgarlic", "Ketchupspicy", "Chips",
"Chipsorganic")))