this is ugly, but... l <-length(patrn) l2 <-length(exmpl)
out <- vector("list") for(i in 1:(l2-l+1)) { exmpl[i:(i+l-1)] patrn==exmpl[i:(i+l-1)] if(all(patrn==exmpl[i:(i+l-1)])) { out[[i]] <- i } else { out[[i]] <- "NA"} } out <- do.call(c, out) as.numeric(out[which(out!="NA")]) ## Cheers and HTH Redding, Matthew-2 wrote > > Hi All, > > > I've been trawling through the documentation and listserv archives on this > topic -- but > as yet have not found a solution. I'm sure this is pretty simple with R, > but I cannot work out how without > resorting to ugly nested loops. > > As far as I can tell, grep, match, and %in% are not the correct tools. > > Question: > given these vectors -- > 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) > > how do I get the desired answer by finding the occurence of the pattern > and returning the starting indices: > 6, 13, 23 > > Suggestions very much appreciated! > > Kind regards, > > > > > Matt Redding, Ph.D. > Principal Scientist > Geochemist/Soil Chemist > Queensland Primary Industries & Fisheries > DEEDI > PO Box 102, Toowoomba, 4350, Qld > ph: 0746 881372 > fax: 0746 881192 > > > ********************************DISCLAIMER**************...{{dropped:15}} > > ______________________________________________ > R-help@ mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > -- View this message in context: http://r.789695.n4.nabble.com/matching-a-sequence-in-a-vector-tp4389523p4389560.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.