5

I have a vector called data which has approximately 35000 elements (numeric). And I have a numeric vector A. I want to remove every appearance of elements of A in the vector data. For example if A is the vector [1,2]. I want to remove all appearance of 1 and 2 in the vector data. How can I do that? Is there a built in function that does this? I couldn't think of a way. Doing it with a loop would take a long time I assume. Thanks!

mathstackuser123
  • 305
  • 2
  • 4
  • 7
  • 1
    Your question is not clear and you don't include a reproducible example. Maybe you are looking for a set difference, `?setdiff`. – lmo Mar 24 '17 at 18:01
  • @lmo, Thanks. I guess setdiff works.I thought my example was clear. I just want to remove all the appearances of elements of A from the data vector. I gave the example [1,2] . The element 1 for example might appear 1000 (or not at all) times in data vector, and I want to delete all of them, and same for 2. I thought this was clear. – mathstackuser123 Mar 24 '17 at 18:39
  • 1
    If you continue to post R questions, you should read [how to create a great R example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and follow that advice. (not my downvote, btw). – lmo Mar 24 '17 at 18:50

1 Answers1

16

There is this handy %in%-operator. Look it up, one of the best things I can think of in any programming language! You can use it to check all elements of one vector A versus all elements of another vector B and returns a logical vector that gives the positions of all elements in A that can be found in B. It is what you need! If you are new to R, it might seem a bit weird, but you will get very much used to it.

Ok, so how to use it? Lets say datvec is your numeric vector:

datvec = c(1, 4, 1, 7, 5, 2, 8, 2, 10, -1, 0, 2)
elements_2_remove = c(1, 2)

datvec %in% elements_2_remove
## [1]  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE

So, you see a vector that gives you the positions of either 1 or 2 in datvec. So, you can use it to index what yuo want to retain (by negating it):

datvec = datvec[!(datvec %in% elements_2_remove)]

And you are done!

rpatel
  • 576
  • 1
  • 6
  • 20
Calbers
  • 399
  • 3
  • 4