Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing certain elements from a vector in R [duplicate]

Tags:

r

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!

like image 574
mathstackuser123 Avatar asked Dec 14 '22 23:12

mathstackuser123


1 Answers

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!

like image 68
Calbers Avatar answered Jan 08 '23 18:01

Calbers