Skip to content
Prev 304392 / 398506 Next

Search for locations of subsequences?

Hello,

Try the following.

occur1 <- function(pat, vec){
     m <- length(pat)
     n <- length(vec)
     candidate <- seq.int(length=n-m+1)
     for (i in seq.int(length=m))
         candidate <- candidate[pat[i] == vec[candidate + i - 1]]
     candidate
}

patrn <- c(1,2,3,4)
exmpl <- c(3,3,4,2,3,1,2,3,4,8,8,23,1,2,3,4,4,34,4,3,2,1,1,2,3,4)

occur1(patrn, exmpl)
[1]  6 13 23

This was posted some time ago. And seems to be the fastest of the 7 
solutions.
https://stat.ethz.ch/pipermail/r-help/2012-February/303756.html

Hope this helps,

Rui Barradas

Em 28-08-2012 22:05, Duncan Murdoch escreveu: