If you have a vector of strings and you want to know which match. It's 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 you would like to find which X are not in Y?
A neat way that I like (that I learnt from @joran, iirc) is:
`%nin%` <- Negate(`%in%`)
which(x %nin% y)
[1] 1 3
Doing %in%
returns a vector of trues and falses. Using an exclamation mark will turn those Ts and Fs around, and by wrapping everything in which
will give you indices.
> which(!x %in% y)
[1] 1 3
> which(x %in% y)
[1] 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With