Step by step majority vote

2

I would like to know how I can calculate the majority vote step by step, for example, comparing column 1 with 2, per line , then 1,2 and 3, per line , then 1, 2, 3 and 4, per line , and so on.

set.seed(1)
a = matrix(sample(1:6, 30, replace = T), ncol = 5)

That is, I get the line i I compare all the elements, I calculate the element that appears the most times and return the same, being output as an array with i rows and j-1 columns.     

asked by anonymous 12.09.2015 / 16:29

1 answer

3

One way:

sapply(2:ncol(a), function(x) apply(a, 1, function(y) names(which.max(table(y[1:x])))))
     [,1] [,2] [,3] [,4]
[1,] "2"  "2"  "2"  "2" 
[2,] "3"  "3"  "3"  "3" 
[3,] "4"  "4"  "4"  "4" 
[4,] "1"  "1"  "1"  "3" 
[5,] "2"  "2"  "2"  "2" 
[6,] "2"  "6"  "6"  "6" 

The first column of the result compares only columns 1 and 2 of the a array to each of the 5 rows. The second column of the result compares columns 1, 2, and 3 of the a array to each of the 5 rows and so on.

    
12.09.2015 / 19:45