20

Possible Duplicate:
How to delete multiple values from a vector?

Is there any build-in function allowing us to remove a particular group of elements in a vector ?

example:

x<-c(2, 4, 6, 9, 10)

remove the vector c(4,9,10) from x

0

3 Answers 3

27

you can do this many ways here is one:

x[!x %in% c(4, 9, 10)]
1
  • if you want to use which, you can do: x[which(!x %in% c(4,9,10))]
    – Kay
    Aug 8, 2019 at 12:12
11

Alternatively you could use ?is.element

x[!is.element(x, c(4,9,10))]
1
  • You forgot the close paren on is.element. Jul 26, 2012 at 15:26
8

This could be useful

 x<-c(2, 4, 6, 9, 10)
 y <- c(4,9,10)
 setdiff(x, y)
 2 6
2
  • Only caveat here is that setdiff performs a set operation. So if x <-c(2,4,6,9,10,2), then setdiff still returns 2 6 where one might expect 2 6 2. Jul 26, 2012 at 17:01
  • 1
    @mindless.panda you're completely right, in that case one should use x[!x%in%y] as jmsigner suggests. Jul 26, 2012 at 17:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.