Majority vote step by step

Asked

Viewed 59 times

2

I would like to know how I can calculate the majority vote step by step, for example by 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)

I mean, I take the line i compare all elements, calculate the element that appears the most times and return the same, being as output a matrix with i lines and j-1 columns .

  • 1

    You edited the question but did not return Carlos' answer. She does not answer you? If not, why? Comment on his response so he can adapt the code, no doubt possible. It would be better if you post the desired output beyond the explains in his text.

  • Learning politics yet, rsrs. Grateful!

1 answer

3


A 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 matrix a for each of the 5 rows. The second column of the result compares columns 1, 2 and 3 of the matrix a for each of the 5 lines and so on.

  • Carlos, I edited the question, because the answer was not as expected. I hope that fixed a row the elements are compared column by column and return the comparison of two columns, three etc. The output element b[1,1,] for that seed would be, 2 or 6, the b[1,2,] 2 or 6 or 5, the a[1,3,] 2 or 6 or 5 or 3 and the a[1,4,] would be 2. Then the same for the other output lines. .

  • 1

    Okay, so you don’t want the biggest element, but the one that comes up the most times, I edited the answer .

  • 1

    That’s right Carlos, thanks again. You have saved a master’s degree (rsrsrs). .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.