Count the number of occurrences in the index of the vector

I am currently working on optimizing the R code. So I try to avoid dynamic memory allocation, FOR loop, ... But I have some difficulties with some FOR loop, I need to create this behavior:

INPUT:

v <- c(TRUE,FALSE,FALSE,TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE)

      

OUTPUT:

 [1] 0 0 0 1 1 2 3 3 3 3

      

I think the easiest way is to count the number of "TRUE" cases for the current index of the vector. If you have an idea ... Don't forget to avoid the FOR loop and don't optimize your code.

thank

+3


source to share


1 answer


This is the trick:



cumsum(v)-1L

      

+3


source







All Articles