# [R] times 'til first change

Thomas Lumley tlumley at u.washington.edu
Mon Oct 29 23:30:35 CET 2001

```On Mon, 29 Oct 2001, Claudia Tebaldi wrote:

> There is probably an elegant and efficient way to do this -- perhaps
> already implemented, and some of you knows it. Myself, I'm getting stuck
> in long loops ...
>
> Here is the question:
>
> I have a long (80,000 + obs) binary time series.
> For each of its elements I'd like to compute and save in a vector "the
> number of steps 'til the first switch of state happens". For example, say
> the first 10 obs of my x series look like
>
>                  0 0 1 0 1 1 1 1 0 1
>
> I want to come up with a 9-component y vector that looks like
>
>                  2 1 1 1 4 3 2 1 1
>
> (it took two steps for the state to change from 0 to 1 if I take the first
> obs as the state of reference, one step if i take the second obs as
> reference ... and so on).

In this case without missing values I think this works
cumsum(diff(x)!=0)->l
y<-do.call("c",lapply(split(x,c(0,l)),function(r) length(r):1))

or something similar with rle()

> I don't care about distinguishing changes from 0 to 1 from their opposite,
> but I'd like to have NAs appear in the derived series in case NAs appeared
> in the original time series BEFORE a switch, say
>
>              x    0 0 1 0 1 1 1 NA 0 1.....
>
> should originate
>
>              y    2 1 1 1 NA NA NA NA 1....
>
> because for the series of 1's starting in the 5th position I really don't
> know if the switch happened at the 8th or at the 9th step.
>

This is a little trickier

If the NAs were sparse enough you could do

x1<-ifelse(is.na(x),1,x)
x0<-ifelse(is.na(x),0,x)

then generate y1 and y0 and do
y1[y1!=y0]<-NA
but I'm not sure that this works if you have two NAs close together.

-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```