Dail Dail - 1 month ago 7
R Question

How to delete multiple values from a vector?

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.

Answer

The %in% operator tells you which elements are among the numers to remove:

> a <- sample (1 : 10)
> remove <- c (2, 3, 5)
> a
 [1] 10  5  2  7  1  6  3  4  8  9
> a %in% remove
 [1] FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
> a [! a %in% remove]
 [1] 10  7  1  6  4  8  9