How to save the address of the equal elements between vector and array?

1

I'm in doubt, I'd like to get the element a[1] and compare with b[1,1] and count as success, then the a[2] element compared to b[2,1] and so on, always per column. Then I want to compare a[1] with b[1,2] and count as right, then the a[2] element with the b[2,2] element and so on. Then return the column of b to which you got the most hits.

set.seed(1)
a = sample(1:3, 4, replace = T) 
b = matrix(sample(1:3, 20, replace = T), ncol = 5, byrow = T)

The desired answer would be column 2 or 5 that would tie randomly to one of the columns.

Thank you in advance.

    
asked by anonymous 30.09.2015 / 16:29

1 answer

2

Try this:

> set.seed(1)
> a = sample(1:3, 4, replace = T) 
> b = matrix(sample(1:3, 20, replace = T), ncol = 5, byrow = T)
> a
[1] 1 2 2 3
> b
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    3    2    2
[2,]    1    1    1    3    2
[3,]    3    2    3    3    2
[4,]    3    3    1    2    1
> comparacoes <- apply(b, 2, function(x) x == a)
> comparacoes
      [,1]  [,2]  [,3]  [,4]  [,5]
[1,]  TRUE FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE FALSE  TRUE
[3,] FALSE  TRUE FALSE FALSE  TRUE
[4,]  TRUE  TRUE FALSE FALSE FALSE
> somas <- colSums(comparacoes)
> somas
[1] 2 2 0 0 2
> b[,nnet::which.is.max(somas)]
[1] 1 1 3 3

Use apply , to compare column-by-column vector elements with those of array. The colSums to identify the number of "hits" per column. And the which.is.max to catch the maximum, and if there is tie, catch randomly.

I just found it strange that you say that the result could be column 2 or 5, but apparently 1 also falls into this situation.

    
30.09.2015 / 18:37