Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subset a dataset using multiple exclusions?

Tags:

r

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.

like image 703
vatodorov Avatar asked Feb 20 '23 12:02

vatodorov


2 Answers

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%

like image 101
GSee Avatar answered Feb 23 '23 16:02

GSee


Try again:

library(operators) 

x%!in%y  

#works fine 
like image 22
Carl Witthoft Avatar answered Feb 23 '23 14:02

Carl Witthoft