I have a vector like: a = c(1:10)
and I need to remove multiple values, like: 2, 3, 5
How to delete those numbers (they are NOT the positions in the vector) in the vector?
at the moment i loop the vector and do something like:
a[!a=NUMBER_TO_REMOVE]
But I think there is a function that does it automatically.
Best Answer
The
%in%
operator tells you which elements are among the numers to remove:Note that this will silently remove incomparables (stuff like
NA
orInf)
as well (while it will keep duplicate values ina
as long as they are not listed inremove
).If
a
can contain incomparables, butremove
will not, we can usematch
, telling it to return0
for non-matches and incomparables (%in%
is a conventient shortcut formatch
):incomparables = 0
is not needed as incomparables will anyways not match, but I'd include it for the sake of readability.This is, btw., what
setdiff
does internally (but without theunique
to throw away duplicates ina
which are not inremove
).If
remove
contains incomparables, you'll have to check for them individually, e.g.(This does not distinguish
NA
fromNaN
but the R manual anyways warns that one should not rely on having a difference between them)For
Inf
/-Inf
you'll have to check bothsign
andis.finite