[R] local sequence function

Martin Maechler maechler at stat.math.ethz.ch
Mon Sep 14 17:31:37 CEST 2009

>>>>> "s" == smu  <ml at z107.de>
>>>>>     on Mon, 14 Sep 2009 17:20:27 +0200 writes:

    s> hey, I can not find a function for the following problem,
    s> hopefully you can help me.

    s> I have a vactor like this one


    s> and I would like to the TRUE values by the their "local
    s> sequence number".

    s> This means, the result should look thike this:

    s> c(NA,NA,1,2,NA,1,NA,1,2,3)

    s> Of course I could solve the problems using a loop, but
    s> this would be much to slow, because the real vector is
    s> much larger.  Can you point me in the right direction?

Ok, something along

> lapply(lapply(split(v, cumsum(is.na(v))), `[`, -1L), seq_along)

[1] 1 2

[1] 1

[1] 1 2 3

Martin Maechler, ETH Zurich

More information about the R-help mailing list