Search code examples
rdataframesubset

Opposite of %in%: exclude rows with values specified in a vector


A categorical variable V1 in a data frame D1 can have values represented by the letters from A to Z. I want to create a subset D2, which excludes some values, say, B, N and T. Basically, I want a command which is the opposite of %in%

D2 = subset(D1, V1 %in% c("B", "N", "T"))

Solution

  • You can use the ! operator to basically make any TRUE FALSE and every FALSE TRUE. so:

    D2 = subset(D1, !(V1 %in% c('B','N','T')))
    

    EDIT: You can also make an operator yourself:

    '%!in%' <- function(x,y)!('%in%'(x,y))
    
    c(1,3,11)%!in%1:10
    [1] FALSE FALSE  TRUE