Search for strings not% in% of another string vector

If you have a row vector and you want to know what a match. This is a simple matter of using% in%.

x <- c("red","blue","green")
y <- c("yellow","blue","orange")

which(x %in% y) # Literally, which X are in Y.

But what about the opposite, where would you like to find which X are not in Y?

+5
source share
2 answers

The clean way I like (which I learned from @joran, iirc) is:

`%nin%` <- Negate(`%in%`)
which(x %nin% y)
[1] 1 3    
+8
source

Execution %in%returns a vector of rights and falsehoods. Using an exclamation mark will cause Ts and Fs to be surrounded, and by wrapping everything in which, you get indexes.

> which(!x %in% y)
[1] 1 3
> which(x %in% y)
[1] 2
+5
source

All Articles