Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding strings not %in% other vector of strings [duplicate]

Tags:

r

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?

like image 854
Brandon Bertelsen Avatar asked Apr 05 '13 22:04

Brandon Bertelsen


2 Answers

A neat way that I like (that I learnt from @joran, iirc) is:

`%nin%` <- Negate(`%in%`)
which(x %nin% y)
[1] 1 3    
like image 196
Arun Avatar answered Oct 23 '22 09:10

Arun


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
like image 23
Roman Luštrik Avatar answered Oct 23 '22 10:10

Roman Luštrik