R, whether all the elements of X are present in Y

前端 未结 3 1921
忘掉有多难
忘掉有多难 2021-01-20 23:26

In R, how do you test for elements of one vector NOT present in another vector?

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


        
相关标签:
3条回答
  • 2021-01-21 00:13

    You can use all and %in% to test if all values of X are also in Y:

    all(X %in% Y)
    #[1] TRUE
    
    0 讨论(0)
  • 2021-01-21 00:19

    A warning about setdiff : if your input vectors have repeated elements, setdiff will ignore the duplicates. This may or may not be what you want to do.

    I wrote a package vecsets , and here's the difference in what you'll get. Note that I modified 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"
    
    0 讨论(0)
  • 2021-01-21 00:21

    You want setdiff:

    > setdiff(X, Y) # all elements present in X but not Y
    character(0)
    
    > length(setdiff(X, Y)) == 0
    [1] TRUE
    
    0 讨论(0)
提交回复
热议问题