matching a sequence in a vector?
On Tue, Feb 14, 2012 at 11:17 PM, Redding, Matthew
<Matthew.Redding at deedi.qld.gov.au> wrote:
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
Here is a one-liner: library(zoo) which(rollapply(exmpl, 4, identical, patrn, fill = FALSE, align = "left"))
Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com