3

I am currently working on optimization of a 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 a behaviour like this :

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 will be to be able to count the number of occurence of "TRUE" to the current index of the vector. If you have any idea ... Remember to avoid FOR loop and non-optimize code.

Thanks

  • 7
    `cumsum(v)-1L` does it – Frank Jul 01 '15 at 16:40
  • @Frank: Looks like an excellent solution to me. Why not posting it as an answer? – RHertel Jul 01 '15 at 17:44
  • @RHertel Okay. I was inclined not to because the question doesn't seem of much general use. (Like, I can't see a connection between the title and the desired behavior strong enough that someone could land here via search engine.) The question's well-posed, so I'm not inclined to close it, though. – Frank Jul 01 '15 at 17:47
  • Also, I guess there's a dupe... – Frank Jul 01 '15 at 17:47

1 Answers1

3

This does the trick:

cumsum(v)-1L
Frank
  • 66,179
  • 8
  • 96
  • 180