Majority matrix vote in R

3

I want to compare elements of an array, for example, in line 1 (fixed) I want to know which object happens most frequently and return the same, I need it automated, because the number of columns is variable.

Here is an example of the code:

M = 3
a = matrix(sample(1:2, 300, replace = T), ncol = M)
combinado = rep(0, nrow(a))

i = 1
while(i <= nrow(a)){
  if(sum(a[i,]) == 3||sum(a[i,]) == 4) combinado[i] = 1
  else combinado[i] = 2
  i = i + 1
}

Where I would like to vary the M, respecting the size of the light matrix.

    
asked by anonymous 04.09.2015 / 15:08

2 answers

3

You can easily do this using a combination of apply with table :

count <- apply(a, 1, function(r) as.numeric(names(which.max(table(r)))))

We have to use as.numeric because names returns a string result.

Demonstrating the result:

> identical(combinado, count)
[1] TRUE
    
04.09.2015 / 20:51
2

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"
    
04.09.2015 / 20:45