Jay
Jay

Reputation: 751

How do I filter two matrices based on common values in a column?

I am trying to filter two matrices based on the first column

a <- matrix(c("b", "s", "a", "w", "r", "te", "fds", "s", "h", "a", "df", "tyi"), nrow = 4)
colnames(a) <- c("fir", "sec", "thi")


     fir sec   thi  
[1,] "b" "r"   "h"  
[2,] "s" "te"  "a"  
[3,] "a" "fds" "df" 
[4,] "w" "s"   "tyi"

b <- matrix(c("a","b","c","d", "e", "f", "g", "h", "i"), nrow = 3)
colnames(b) <- c("fir", "sec", "thi")


    fir sec thi
[1,] "a" "d" "g"
[2,] "b" "e" "h"
[3,] "c" "f" "i"

Basically what I want to do is subset matrix a based on the hits in b[,1] So since (row1, col1) and (row3, col1) in matrix a match certain values in column 1 in matrix b, I'd like to extract those two rows.

I appreciate any tips and advice. Thank you.

Also, can someone explain why this doesn't work?

> c <- intersect(a[,1], b[,1])
> c
[1] "b" "a"
> a[a[,1]==c]
[1] "b" "r" "h"

Upvotes: 0

Views: 191

Answers (1)

Karan
Karan

Reputation: 284

You could try this, although there may be a more elegant way to do it.

matched <- a[,1] %in% b[,1]
a[matched,]

Upvotes: 3

Related Questions