0

I have two Matrix with different width.


Matrix_A
  'data.frame':412 obs. of  5 variables:
 $ R : num  2 18 18 2 2 18 18 2 2 2 ...
 $ NS: num  4.82e+09 4.82e+09 4.82e+09 4.82e+09 4.82e+09 ...
 $ NP: chr  "20000070000" "20000000090000" "20000000060000" "20000000010000" ...
 $ NG: chr  "TE" "EC" "ET" "HT" ...
 $ DC : logi  NA NA NA NA NA NA ...

Matrix_B

  'data.frame': 2687 obs. of  4 variables:
 $ R : num  18 2 2 2 18 2 2 2 18 2 ...
 $ NS : num  4.81e+09 4.81e+09 4.81e+09 4.81e+09 4.81e+09 ...
 $ NP :chr  "20000000000400" "2000000000600" "2000000001000" "20000000007000" ...
 $ NG: chr  "HT" "HT" "TT" "TY" ... 

I would like to know what elements of the Matrix A are present in the Matrix B, and to do this I wrote this code.


Matrix_B$Results <- ifelse((Matrix_A$R %in% Matrix_B$R), 
                           ifelse((Matrix_A$NS %in% Matrix_B$NS),1,0))

This dosen't give me a error, but the result is not correct.

I tried this


Matrix_B$Results <- ifelse((Matrix_A$R %in% Matrix_B$R) & 
                        (Matrix_A$NS %in% Matrix_B$NS),1,0))

but dosen't work.

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
Earl Mascetti
  • 1,278
  • 3
  • 16
  • 31
  • The other possible dupe is [Why are these numbers not equal?](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal). See column `Matrix_A$NS`. – Rui Barradas Aug 27 '18 at 12:35
  • @phiver i don't think this question directly asks about `merging`. Could you please give me a feedback about my solution? – Sal-laS Aug 27 '18 at 13:00
  • I think that is not a duplicate, because I don't want to join these two table. I would like to know if one element of Matrix A is present in Matrix B. But maybe the correct way is to use the merge or join. – Earl Mascetti Aug 27 '18 at 14:21

1 Answers1

0

I would like to know what elements of the Matrix A are present in the Matrix B

Indeed it is subtraction of two collections:

A<-matrix( sample(1:5,12,replace = T ), 4, 3) 

 B<-matrix( sample(1:10,10,replace = T ), 2, 5)

So, the matrix A, and B could be:

> A
     [,1] [,2] [,3]
[1,]    4    3    3
[2,]    2    1    5
[3,]    4    4    5
[4,]    1    4    4
> B
     [,1] [,2] [,3] [,4] [,5]
[1,]    4    3   10    8    9
[2,]    1   10   10    9    6

Now if you wish to know, which elements are in both matrixes, you have 2 options:

Approach 1:

intersect(B,A)

Approach 2:

existInANotB<-setdiff(A,B)
intersect<-setdiff(A,existInANotB)
Sal-laS
  • 11,016
  • 25
  • 99
  • 169