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!

3
  • 1
    Your question is not clear and you don't include a reproducible example. Maybe you are looking for a set difference, ?setdiff. Commented Mar 24, 2017 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. Commented Mar 24, 2017 at 18:39
  • 1
    If you continue to post R questions, you should read how to create a great R example and follow that advice. (not my downvote, btw). Commented Mar 24, 2017 at 18:50

1 Answer 1

17

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.