0

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"
2
  • 1
    The reason your code doesn't work is that you're using == instead of %in%.
    – josliber
    Jul 16, 2014 at 20:45
  • @josilber Appreciate it. Didn't know about this operator til now
    – Jay
    Jul 23, 2014 at 20:03

1 Answer 1

3

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.