Speed up a function that checks for a sequence I created a  function yes.seq that takes two arguments, a pattern pat and data dat, the function looks for the presence of a pattern in the data and in the same sequence.
For example:
dat &lt;- letters[1:10]
dat
[1] &quot;a&quot; &quot;b&quot; &quot;c&quot; &quot;d&quot; &quot;e&quot; &quot;f&quot; &quot;g&quot; &quot;h&quot; &quot;i&quot; &quot;j&quot;
pat &lt;- c('a',&quot;c&quot;,&quot;g&quot;)
 
 yes.seq(pat = pat,dat = dat)
[1] TRUE

because this sequence is in the pattern and in the same order.
&quot;a&quot; &quot;b&quot; &quot;c&quot; &quot;d&quot; &quot;e&quot; &quot;f&quot; &quot;g&quot; &quot;h&quot; &quot;i&quot; &quot;j&quot;
If, for example, we reverse the pattern, then we get FALSE:
yes.seq(pat = pat,dat =  **rev(dat)**   )
[1] FALSE

Here is my function:
yes.seq &lt;- function(pat , dat){  
  lv &lt;- rep(F,length(pat))
  k &lt;- 1     
  for(i in 1:length(dat)){        
            if(dat[i] == pat[k]) 
              {
              lv[k] &lt;- TRUE
              k &lt;- k+1 
              }       
    if(k==length(pat)+1) break
  }
  return(  all(lv)   )
}

I am not satisfied with the speed of this function.  Can you help me with that?
Here is a vectorized version:
yes.seq &lt;- function(dat, pat) {
  paste(dat[dat %in% pat], collapse = &quot;&quot;) == paste(pat, collapse = &quot;&quot;)
}

yes.seq(dat, pat)
# [1] TRUE
yes.seq(dat, rev(pat))
# [1] FALSE