R whether all elements of X are present in Y

In R, how do you check for elements of one vector that are not present in another vector?

X <- c('a','b','c','d')
Y <- c('b', 'e', 'a','d','c','f', 'c')

      

I want to know if all X elements are present in Y? (TRUE or FALSE)

+3


source to share


3 answers


You want setdiff

:



> setdiff(X, Y) # all elements present in X but not Y
character(0)

> length(setdiff(X, Y)) == 0
[1] TRUE

      

+2


source


You can use all

and %in%

to check if all values ​​are X

in Y

:



all(X %in% Y)
#[1] TRUE

      

+3


source


Warning setdiff

: if your input vectors have duplicate elements, setdiff

duplicates will be ignored. This may or may not be what you want to do.

I wrote a package vecsets

and here is the difference in what you get. Please note that I have changed X

to demonstrate the behavior.

 library(vecsets)
 X <- c('a','b','c','d','d')
 Y <- c('b', 'e', 'a','d','c','f', 'c')
 setdiff(X,Y)
   character(0)
 vsetdiff(X,Y)
[1] "d"

      

+2


source







All Articles