[R] Count matches of a sequence in a vector?

Gabor Grothendieck ggrothendieck at gmail.com
Wed Apr 21 22:15:46 CEST 2010


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.
>



More information about the R-help mailing list