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

r vector

95 просмотра

3 ответа

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', 'c')

I want to know whether all the elements of X are present in Y ? (TRUE or FALSE answer)

Автор: d.putto Источник Размещён: 12.11.2019 09:26

Ответы (3)

2 плюса


You want setdiff:

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

> length(setdiff(X, Y)) == 0
[1] TRUE
Автор: TMS Размещён: 05.12.2014 12:43

3 плюса

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

all(X %in% Y)
#[1] TRUE
Автор: docendo discimus Размещён: 05.12.2014 12:46

2 плюса

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.

 X <- c('a','b','c','d','d')
 Y <- c('b', 'e', 'a','d','c','f', 'c')
[1] "d"
Автор: Carl Witthoft Размещён: 05.12.2014 12:57
Вопросы из категории :