-1

I am programming in R and I have two matrices, like this

a:    x1     x2                 b:   x1
      5      3                       3
      5      10                      5
      7      3                       7 
      7      140                     8
      10     152                     10
      ...    ...                     ...

I want to remove all rows in b, where b$x1 is neither the same as any a$x1 or b$x1. If the x1 of matrix b is the same as any x1 or x2 in a, then it should stay in matrix b. The matrices also have other columns, but they are not interesting for this operation.

Can anybody help me?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • Please read [here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) on how to make your dummy data easily available for people that wants to help you. Please also show what you tried. [Questions asking for code must include attempted solutions, why they didn't work, and the expected results](http://stackoverflow.com/help/on-topic). Thanks! – Henrik Oct 25 '13 at 20:44

1 Answers1

2

I'm not sure If I've properly understood what are you asking but you can try like that

> a
     x1  x2
[1,]  5   3
[2,]  5  10
[3,]  7   2
[4,]  7 140
[5,] 10 152

> b
     x1
[1,]  3
[2,]  5
[3,]  7
[4,]  8
[5,] 10

> as.matrix(b[which(b %in% a[,c(1,2)])])

         [,1]
    [1,]    3
    [2,]    5
    [3,]    7
    [4,]   10

And bear in mind that both "a" and "b" must be matrices and furthermore, the outcome of that function will result in a matrix with less rows, you can easily expand the operation if you have more columns.

EDIT

OK, no big problem, but you specified that both where matrices or perhaps, I misread, whatever. I edit with the same operation with data frames but still left the matrices for anyone who could need it.

> subset(b, b$x1 %in% c(a$x1,a$x2))
  x1
1  3
2  5
3  7
5 10

You can also establish the index to be like b[[index]] instead of using names built-in data frame reference

Diego Jimeno
  • 312
  • 4
  • 15