Hey there, I need to count the matches of a sequence seq=c(2,3,4) in a long vector v=c(4,2,5,8,9,2,3,5,6,1,7,2,3,4,5,....). With sum(v %in% seq) I only get the sum of sum(v %in% 2), sum(v %in% 3) and sum(v %in% 4), but that's not what I need :( Who can help me? Thanks a lot! -- View this message in context: http://n4.nabble.com/Count-matches-of-a-sequence-in-a-vector-tp2019018p2019018.html Sent from the R help mailing list archive at Nabble.com.
This sort of calculation can't be vectorized; you'll have to iterate through the sequence, e.g. with a "for" loop. I don't know if a routine has already been written. -- View this message in context: http://n4.nabble.com/Count-matches-of-a-sequence-in-a-vector-tp2019018p2019108.html Sent from the R help mailing list archive at Nabble.com.
One option might be to turn the sequence into a character string, and then use something like grep(). Kind of a kludge, but possibly easy. -- View this message in context: http://n4.nabble.com/Count-matches-of-a-sequence-in-a-vector-tp2019018p2019161.html Sent from the R help mailing list archive at Nabble.com.
rollapply in the zoo package could be used: library(zoo) ix <- rollapply(zoo(v), 3, function(x) all(x == 2:4)) which returns a logical vector or if you want the indexes use this: which(ix) On Wed, Apr 21, 2010 at 10:16 AM, mieke <hcS_ffetS at gmx.de> wrote:> > Hey there, > > I need to count the matches of a sequence seq=c(2,3,4) in a long vector > v=c(4,2,5,8,9,2,3,5,6,1,7,2,3,4,5,....). > With sum(v %in% seq) I only get the sum of sum(v %in% 2), sum(v %in% 3) and > sum(v %in% 4), but that's not what I need :( > > Who can help me? > Thanks a lot! > -- > View this message in context: http://n4.nabble.com/Count-matches-of-a-sequence-in-a-vector-tp2019018p2019018.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at 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. >