Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if vector contains another vector

Tags:

r

I want to check whether a vector y contains another vector x

y <- c(0,0,0,NA,NA,0)
x <- c(0,0,0,0)

In this case, it should give me FALSE because there is no sequence of four NULL in y. But if we take a look at vector y2, the result should be TRUE.

y2 <- c(0,0,NA,0,0,0,0)

EDIT:

I tried to use %in% but it seems to only work for elements of vectors, not for whole vectors. The solution doesn't have to be applicable to more general problems. It would be nice if it works for this particular case.

like image 816
beginneR Avatar asked Sep 10 '13 13:09

beginneR


1 Answers

You can use a combination of grepl and paste. Here you need to collapse each vector into one character using the collapse argument in paste.

> grepl(paste(x,collapse=";"),paste(y2,collapse=";"))
[1] TRUE
> grepl(paste(x,collapse=";"),paste(y,collapse=";"))
[1] FALSE

> grepl(paste(c(123),collapse=";"),paste(c(12,3),collapse=";"))
[1] FALSE
like image 55
dayne Avatar answered Sep 18 '22 17:09

dayne