# [R] times 'til first change

Claudia Tebaldi tebaldi at rap.ucar.edu
Mon Oct 29 20:30:15 CET 2001

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

claudia

-------------------------------------------------------------------------
claudia tebaldi                                  NCAR  RAP
project scientist                                P.O. Box 3000
(303) 497-2830                                   Boulder, CO 80307
--------------------------------------------------------------------------

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

```