[R] sort of cumulative counting in a vector

Benilton Carvalho bcarvalh at jhsph.edu
Thu Nov 5 14:34:44 CET 2009


You will get 0s instead of NAs, but this may suffice:

cumsum(test == 't')

b

On Nov 5, 2009, at 11:30 AM, Stefan Uhmann wrote:

> Dear list,
>
> I need help, since I can not come up with an easy solution to convert
> this vector
>
> test <- c('p','p','t','t','t')
>
> to
>
> [1] NA NA  1  2  3
>
> which means the occurences of 't' should be summed up at the
> corresponding positions. The solution should also be able to handle  
> the
> following scenarios:
>
> test2 <- c('t','t','t')
>
> [1] 1  2  3
>
> test3 <- c('p','p')
>
> [1] NA NA
>
> test <- c('p','p','t','t','t','p','k','t')
>
> [1] NA NA  1  2  3 NA NA 4
>
>
> I would really appreciate an easy solution!
>
> Thanks,
> 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.




More information about the R-help mailing list