As you want to know the highest frequency value on each line, I'd suggest doing% w_ of% of function% w_ of% per line and then checking the value of highest frequency:
sapply(lapply(split(a, row(a)), table), function(x) names(which.max(x)))
[1] "2" "1" "2" "2" "2" "1" "1" "1" "1" "1" "1" "1" "2" "2" "1" "1" "1" "1" "2" "1" "2"
[22] "1" "1" "2" "1" "1" "2" "1" "1" "1" "2" "1" "2" "2" "2" "2" "1" "1" "1" "2" "2" "1"
[43] "2" "2" "1" "2" "2" "1" "2" "1" "1" "1" "1" "2" "1" "2" "1" "2" "1" "2" "1" "2" "2"
[64] "1" "2" "1" "2" "1" "2" "1" "2" "2" "2" "2" "2" "1" "1" "2" "2" "1" "2" "2" "1" "2"
[85] "1" "2" "1" "2" "2" "1" "1" "1" "1" "2" "1" "2" "1" "1" "1" "2"
Demonstrating that the results are the same as yours:
all.equal(combinado, as.numeric(sapply(lapply(split(a, row(a)), table), function(x) names(which.max(x)))))
[1] TRUE
Note that with lapply
, the calculation does not depend on the number of columns in the array. Doing with table
:
M = 5
a = matrix(sample(1:2, 300, replace = T), ncol = M)
sapply(lapply(split(a, row(a)), table), function(x) names(which.max(x)))
[1] "2" "2" "1" "2" "2" "2" "2" "2" "2" "1" "2" "1" "2" "2" "2" "2" "1" "2" "2" "1" "2"
[22] "1" "1" "2" "1" "2" "1" "1" "1" "2" "1" "2" "2" "2" "1" "1" "1" "2" "2" "2" "1" "2"
[43] "2" "2" "2" "2" "1" "1" "2" "1" "2" "2" "1" "2" "2" "1" "2" "2" "2" "2"