63

Possible Duplicate:
Standard way to remove multiple elements from a dataframe

I know in R that if you are searching for a subset of another group or matching based on id you'd use something like

subset(df1, df1$id %in% idNums1)

My question is how to do the opposite or choose items NOT matching a vector of ids.

I tried using ! but get the error message

subset(df1, df1$id !%in% idNums1)

I think my backup is to do sometime like this:

matches <- subset(df1, df1$id %in% idNums1)
nonMatches <- df1[(-matches[,1]),]

but I'm hoping there's something a bit more efficient.

Community
  • 1
  • 1
screechOwl
  • 27,310
  • 61
  • 158
  • 267
  • 7
    see my answer here: http://stackoverflow.com/questions/7494848/standard-way-to-remove-multiple-elements-from-a-dataframe – Chase Mar 24 '12 at 15:19
  • 6
    Or equivalently to Chase's version, my answer [here](http://stackoverflow.com/a/9846035/324364). – joran Mar 24 '12 at 15:23

1 Answers1

129

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)
Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
  • 2
    Remember the extra `()` with if statements. `if (!(something)) { print "not something"}` – Climbs_lika_Spyder May 31 '15 at 17:01
  • The brackets being inconvenient when there are multiple nesting, I have found defining a ``not-in`` operator quite helpful. There are several suggestions on how to do that here: http://stackoverflow.com/questions/5831794/opposite-of-in – PatrickT Oct 27 '15 at 09:23