Namenlos
Namenlos

Reputation: 475

How do I extract pairs of values from matrix cells?

I have two matrices, from which I want to extract all unique pairs of values in corresponding cells. That is, I want to pair the value from cell [1,1] in the first matrix with the cell [1,1] in the second matrix and then reduce that list of pairs to include only the unique pairs. How do I do this?

Here are sample versions of the matrices

     V1  V2  V3  V4  V5  V6 
[1,] "w" "o" "r" "d" NA  NA 
[2,] "p" "o" "r" "c" NA  NA 
[3,] "v" "i" "n" NA  NA  NA 
[4,] "s" "e" "l" NA  NA  NA 
[5,] "p" "i" "e" "d" NA  NA 
[6,] "p" "i" "e" "r" "r" "e"

      V1  V2  V3  V4  V5  V6 
[1,] "h" "a" "e" "d" "a" NA 
[2,] "p" "o" "r" "c" "u" "s"
[3,] "v" "i" "n" "u" "m" NA 
[4,] "s" "a" "l" NA  NA  NA 
[5,] "p" "e" "s" NA  NA  NA 
[6,] "p" "e" "t" "r" "u" "s"

Upvotes: 0

Views: 49

Answers (1)

IRTFM
IRTFM

Reputation: 263451

Couldn't we just do:

unique( paste(m1, m2) )

Testing:

>  m1 <- scan(what="") 
1:  "w" "o" "r" "d" NA  NA 
7:  "p" "o" "r" "c" NA  NA 
13:  "v" "i" "n" NA  NA  NA 
19:  "s" "e" "l" NA  NA  NA 
25:  "p" "i" "e" "d" NA  NA 
31:  "p" "i" "e" "r" "r" "e"
37: 
Read 36 items
>   m2 <- scan(what="")
1:  "h" "a" "e" "d" "a" NA 
7:  "p" "o" "r" "c" "u" "s"
13:  "v" "i" "n" "u" "m" NA 
19:  "s" "a" "l" NA  NA  NA 
25:  "p" "e" "s" NA  NA  NA 
31:  "p" "e" "t" "r" "u" "s"
37: 
Read 36 items
> unique( paste(m1, m2) )
 [1] "w h"   "o a"   "r e"   "d d"   "NA a"  "NA NA" "p p"   "o o"   "r r"   "c c"   "NA u" 
[12] "NA s"  "v v"   "i i"   "n n"   "NA m"  "s s"   "e a"   "l l"   "i e"   "e s"   "d NA" 
[23] "e t"   "r u"  

Upvotes: 2

Related Questions