How to store the address of the equal elements between vector and matrix?

Asked

Viewed 67 times

1

I’m having a question, I’d like to take the element a[1] and compare with b[1,1] and count as a hit, then the element a[2] compared to b[2,1] and so on, always by column. Then I want to compare the a[1] with b[1,2] and count as certain, then the item a[2] with the element b[2,2] and so on. Later return the column of b which got more 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 if tied I choose one of the columns randomly.

Thanks in advance.

  • It’s not very clear. You want to compare the vector a with each of the matrix columns?

  • That, element by element.

  • I edited a stupid question.

1 answer

2


Try it like 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 the apply, to compare column by column the elements of the vector with those of the matrix. The colSums to identify the amount of "hits" per column. And the which.is.max to catch the maximum, and if there is a draw, pick randomly.

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

  • I forgot the column 1. But according to your code the output of the same is not the columns that happen more, ie, 1, 2 or 5.

  • is yes... see the array sums: it is 2 p/ the columns 1, 2 and 5. the following code already selects one of these columns randomly, in case it took the column 1. if you want to get out an array with 1,2 and 5 use which(somas == max(somas)).

  • Got it. I used sort(colSums(comparacoes)) and I was able to verify. Very grateful.

Browser other questions tagged

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