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

Phil Spector spector at stat.berkeley.edu
Wed Apr 21 17:58:34 CEST 2010


If I understand what you're looking for, I think this
may work:

> seq=c(2,3,4)
> v=c(4,2,5,8,9,2,3,5,6,1,7,2,3,4,5)
> lseq = length(seq)
> lv = length(v)
> matches = sapply(1:(lv-lseq+1),function(i)all(v[i:(i+lseq-1)] == seq))
> sum(matches)
[1] 1

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu



On Wed, 21 Apr 2010, Jeff Brown wrote:

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