Home > Enterprise >  Opposite of " %in% " : Error : invalid argument type
Opposite of " %in% " : Error : invalid argument type

Time:12-29

Given this data set:

original_data = data.frame(id = c(1,2,3), a = c("a", "b", "c"), b = c("d", "e", "f"))

I was able to run the following code:

original_data[which(original_data$a %in% c("a", "b") ),]

Now, I am trying to run the "opposite" of this code, but nothing seems to be working:

  original_data[which(original_data$a !%in% c("a", "b") ),]

Error: unexpected '!' in "original_data[which(original_data$a !"

 original_data[which(original_data$a %in%! c("a", "b") ),]

Error in !c("a", "b") : invalid argument type

I even tried the answer suggested over here: Opposite of %in%: exclude rows with values specified in a vector

'%!in%' <- function(x,y)!('%in%'(x,y))

 original_data[which(original_data$a '%!in%' c("a", "b") ),]

Error: unexpected '!' in "original_data[which(original_data$a !"

But nothing is working.

Does anyone know what I am doing wrong?

Thanks!

CodePudding user response:

You're putting the ! in the wrong place. It should be before original_data.

original_data[which(!original_data$a %in% c("a", "b") ),]

Alternatively, you can create a "not in" variable like so:

`%nin%` <- Negate(`%in%`)

You can then use it:

original_data[which(original_data$a %nin% c("a", "b") ),]

CodePudding user response:

Define

 `%notin%` <- Negate(`%in%`) 

and then just use %notin%

original_data[which(original_data$a %notin% c("a", "b") ),]
  •  Tags:  
  • r
  • Related