How to check if a given sequence of elements exists in R?

4

I have a vector like this:

vectorx<-c(3,3,1,1,1,2,2,2,2,2,2,2,2,2)

and I want to check if the sequence 3,3,1,1,1,2 exists. It turns out that this sequence can be in any position of the vector, I just want to know if this sequence specifically exists, I want it to return TRUE or FALSE only. How do I do? I see many% in% but for a sequence that can occur in any position I have not seen yet. Thank you guys

    
asked by anonymous 27.11.2017 / 22:25

2 answers

5
Library(zoo)

vectory <- c(3,3,1,1,1,2)

which(rollapply(vectorx, length(vectory), identical, vectory))

If the output is any number, the vectory sequence is present in vectorx ; otherwise the result will be integer(0)

    
28.11.2017 / 02:45
4

I know the answer has already been accepted, but as you want a response of type TRUE or FALSE follows an alternative:

vectorx <- c(3,3,1,1,1,2,2,2,2,2,2,2,2,2)
vectory <- c(3,3,1,1,1,2)

grepl(paste(vectory, collapse = " "), paste(vectorx, collapse = " "))
    
28.11.2017 / 11:25