[R] making a counter of consecitive positive cases in time series

Marc Schwartz marc_schwartz at comcast.net
Fri Apr 13 05:35:09 CEST 2007


On Thu, 2007-04-12 at 22:30 +0200, Jose Bustos Melo wrote:
> Hi all..RCounters!
>    
>   Im working with standarized time series, and i need make a counter
> of consecutives positves numbers to  make a cumulative experimental
> funtion. I have x: the time series (0,1) and y: my counter, i have
> this for step. What is wrong?.. any can help me please!
>    
>   x<-rbinom(15,1,.3)
>   y<-NULL;s<-0
>   for (i in 1: length (x))
>   {if (x[i]>0)
>   {s<-s+x[i]
>   s=0}
>   else
>   y<-c(y,s)}
>   y
>   x
>    
>    
>   Thk u all!
>   Jos Bustos
>    

I may be mis-understanding your desired result, but is this what you
want:

x <- rbinom(15, 1, .3)

> x
 [1] 1 1 0 0 1 0 0 0 1 1 0 1 1 0 1

> rle(x)
Run Length Encoding
  lengths: int [1:9] 2 2 1 3 2 1 2 1 1
  values : num [1:9] 1 0 1 0 1 0 1 0 1


See ?rle for more information.

HTH,

Marc Schwartz



More information about the R-help mailing list