user8102905
user8102905

Reputation: 191

Filter all rows having 5 or 6 numbers existing in another matrix

Having a matrix A like:

   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]   11   14   17   20   23   26    7    1   10     4    21     3
 [2,]   12   15    8   21   14   27   17   11   19     2     1     3
 [3,]   13   16   19   22   25   28    7   11   10     5    10     4
 [4,]   11   15   28   21    4   27    7    1   12    20    12    23
 [5,]   14   16    9   22   25   28    7    1   13    21    29     3
 [6,]   11    3    6   23   24   26    7    1   14    12    20     4

and a matrix B like:

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] ,15] [,16] [,17] [,18] 
[1,]     2   17   10    4    5    6    7    1    21    20    23    24    11  14     3    26    12    10

I want to get only the rows from matrix A that have only any 5 or any 6 numbers (no more than 5 or 6) existing in matrix B. The Is there an R function I can use to solve it?

I make it easier to understand: matrix A

  1   2   3   4  5
  2   3   5   6  7
  3   5   7   8  1
  2   7   5   4  3

matrix B:

  1   2   4   5   6
  2   4   1   3   7
  3   5   7   9   8
  5   8   9   2   6

if I ask for 5 numbers from B to match rows in A I will get 1 (4th row in B with 2nd row in A).

so this must return only row A2

if I ask for 4 numbers from B to match rows in A I will get :

  B1 - A1
  B2 - A1
  B3 - A1, A2
  B4 - A2

so this must return only row A1, A2

Upvotes: 0

Views: 38

Answers (1)

Smich7
Smich7

Reputation: 460

You can get the number of values which are in B for each row of A with :

counts <- apply(A,1,function(x) sum(!is.na(match(x,B))))

Then, you can get back the rows which have 5 or 6 values in B using :

A_bis <- A[which(counts %in% c(5,6)),]

You can put another condition in the which function if this is not exactly what you want.

Upvotes: 2

Related Questions