How to check if a certain sequence of Elements exists in R?

Asked

Viewed 164 times

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 vector position, I just want to know if specifically this sequence like this 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 haven’t seen yet. Personal thank you

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 sequence vectory is present in the vectorx; otherwise the result will be integer(0)

  • Excellent Willian, that’s exactly it. Thank you so much

  • Do you know a way to return TRUE instead of integer(0)? R: I already solved, I only took which

4

I know the answer has already been accepted, but how do you want an answer like 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 = " "))
  • It works very well too, even I blame myself here because I knew grepl rsrs. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.