0

In a toy problem of mine, I have a vector a made of integers and I want to efficiently remove from a terms that are also in a vector b. I wrote the code

newa=NULL
for (j in 1:length(a))
   if (min(abs(a[i]-b))>0) newa=c(newa,a[i])

but this is terrible...

  • Lots of similar related questions, [here is one](http://stackoverflow.com/questions/7494848/standard-way-to-remove-multiple-elements-from-a-dataframe/7498829#7498829) – Chase Jul 16 '12 at 02:25

2 Answers2

3

You could just use intersect, setdiff, etc (see ?setdiff):

a <- 1:10
b <- c(2, 3, 5, 7)

setdiff(a, b)
# [1]  1  4  6  8  9 10

Or even just use %in%:

a[!(a %in% b)] # (a %in% b) is TRUE in index i if a[i] is in b.
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
2

It's lightening fingers like mathematical.coffee that make it so I never get to answer questions :P

I do this a lot using %in%. And I nabbed a great little bit of code from Stephen Turner that makes it even easier!

## Returns a logical vector TRUE for elements of X not in Y
"%nin%" <- function(x, y) !(x %in% y)
Tom
  • 4,860
  • 7
  • 43
  • 55