Skip to content

sort of cumulative counting in a vector

3 messages · Stefan Uhmann, Benilton Carvalho, Dimitris Rizopoulos

#
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
#
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:

            
#
one approach is the following:

test <- c('p','p','t','t','t','p','k','t')

v <- cumsum(ind <- test == 't')
v[!ind] <- NA
v


I hope it helps.

Best,
Dimitris
Stefan Uhmann wrote: