vatodorov
vatodorov

Reputation: 271

How to subset a dataset using multiple exclusions?

How to combine all state names in a single vector, instead of listing all the logical exclusions separately? I found function %notin% on the CRAN website, but R doesn't recognize is as a legitimate function.

indata <- indata[which(indata$STATE != "GU" & indata$STATE != "WY" &
                       indata$STATE != "KS" & indata$STATE != "ME" &
                       indata$STATE != "MT" & indata$STATE != "ND" &), ]

Thanks.

Upvotes: 4

Views: 583

Answers (2)

GSee
GSee

Reputation: 49810

indata[!indata$STATE %in% c("GU", "WY", "KS", "ME", "MT", "ND"), ]

EDIT: @CarlWitthoft, believe it or not, I've actually had the following in a private package for a while

`%notin%` <- function (x, table) x[!x %in% table]

However, I never think to use it until after I've already typed it out the long way. Plus, using it makes my code less distributable. I was not aware of

operators:::`%!in%`

which is only the second half of %notin%

Upvotes: 5

Carl Witthoft
Carl Witthoft

Reputation: 21492

Try again:

library(operators) 

x%!in%y  

#works fine 

Upvotes: 3

Related Questions