[R] local sequence function

Don MacQueen macq at llnl.gov
Mon Sep 14 17:31:53 CEST 2009


Try this:

>  v <- c(NA,NA,TRUE,TRUE,NA,TRUE,NA,TRUE,TRUE,TRUE)
>  ick <-rle(v)
>  foo <- unlist(apply(matrix(ick$lengths),1,seq))
>  foo[is.na(v)] <- NA
>  foo
  [1] NA NA  1  2 NA  1 NA  1  2  3

-Don

At 5:20 PM +0200 9/14/09, smu wrote:
>hey,
>
>I can not find a function for the following problem, hopefully you can
>help me.
>
>I have a vactor like this one
>
>v = c(NA,NA,TRUE,TRUE,NA,TRUE,NA,TRUE,TRUE,TRUE)
>
>and I would like to the TRUE values by the their "local sequence
>number".
>
>This means, the result should look thike this:
>
>c(NA,NA,1,2,NA,1,NA,1,2,3)
>
>Of course I could solve the problems using a loop, but this would be
>much to slow, because the real vector is much larger.
>Can you point me in the right direction?
>
>thank you!
>
>regards,
>  Stefan
>
>______________________________________________
>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.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list