1

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

jake-ferguson
  • 315
  • 3
  • 11
  • 32
  • Related: [Find a sequence of numbers in a vector](https://stackoverflow.com/questions/48660606/find-a-sequence-of-numbers-in-a-vector) – Henrik Nov 14 '18 at 15:50

1 Answers1

1

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) 
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Hi unfortunately none of ideas are perfect for me - the first one (function) gives me vector so when pat <- c(1, 1), v1 <- c(1,0,1,1,0,0,1,0), v2 <- c(1,0,1,1,1,0,0,1,0) it gives me for example FALSE TRUE FALSE, not just true... and the second one with rleid does't work, when I check pat with my v2 I get true, allthough it should be false :( – jake-ferguson Nov 13 '18 at 21:33
  • 1
    okey that was stupid of me, I just added any to the function and its perfect now :) thanks a lot! – jake-ferguson Nov 13 '18 at 21:36
  • what if I would like to save its' indexes? I know it is kind of another question then... But what if I would like not just find c(1,1) inside let's say c(0,0,1,1,0,1) but remember the indexes so [3,4] in this case... Is it possible? – jake-ferguson Nov 14 '18 at 15:21
  • 1
    @jake-ferguson In that case you may need `which` i.e. `which(pat %in% x)` or `which(sapply(split(...` based on whatever you need – akrun Nov 14 '18 at 16:41