marcus-linmarkson
marcus-linmarkson

Reputation: 363

Find exact vector (with ones) inside 0-1 vector in R

I would like to find a vector inside another vector. I will always look for vectors with only 'ones' inside the vector of zero and ones. For example c(1,1,1) inside c(0,0,1,1,1,0,1). I have already came up with a solution for this:

grepl(paste(x1,collapse=";"),paste(x2,collapse=";"))

The issue is i want to search for exact the vector so

c(1,1) inside c(0,1,1,0) --> TRUE

c(1,1) inside c(0,1,1,1) --> FALSE

Upvotes: 1

Views: 171

Answers (1)

akrun
akrun

Reputation: 887173

We can use rle for this

f1 <- function(vec1, patvec) {
     with(rle(vec1), lengths[as.logical(values)]) == length(patvec)
  }

f1(v1, pat)
#[1] TRUE
f1(v2, pat)
#[1] FALSE

or split the vector by the rleid of vector and then check whether all the elements of pattern vector is found or not

any(sapply(split(v1, data.table::rleid(v1)), function(x) all(pat %in% x)))
#[1] TRUE

data

pat <- c(1, 1)
v1 <- c(0,1,1,0)
v2 <- c(0,1,1,1) 

Upvotes: 1

Related Questions