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.
The
%in%operator tells you which elements are among the numers to remove:Note that this will silently remove incomparables (stuff like
NAorInf)as well (while it will keep duplicate values inaas long as they are not listed inremove).If
acan contain incomparables, butremovewill not, we can usematch, telling it to return0for non-matches and incomparables (%in%is a conventient shortcut formatch):incomparables = 0is not needed as incomparables will anyways not match, but I’d include it for the sake of readability.This is, btw., what
setdiffdoes internally (but without theuniqueto throw away duplicates inawhich are not inremove).If
removecontains incomparables, you’ll have to check for them individually, e.g.(This does not distinguish
NAfromNaNbut the R manual anyways warns that one should not rely on having a difference between them)For
Inf/-Infyou’ll have to check bothsignandis.finite