2

I have a vector, for example

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

and I want to count the number of subsequent "TRUE" values, whereas the counting should start from 1 if there was a "FALSE" value between a block of subsequent "TRUE" values. The result for the example above should be

result <- c(1,0,1,2,0,0,0,1,2,3,0)

Any ideas how to do this nicely?

Giuseppe
  • 786
  • 1
  • 7
  • 18
  • The use of the term 'subsequent' in your question (and title) is misleading (this might be a subtlety of English usage, but I am unsure). The phrase '*count subsequent "TRUE" values*' would be used if you counted how many TRUE's *followed* the current "TRUE", not how many are in the sequence up to and including itself. You need a different word or phrase to express what you want. Perhaps '*cumulative count of run of successive TRUE values*' – Glen_b Mar 11 '14 at 22:14

1 Answers1

4
  • rle computes "the lengths and values of runs of equal values in a vector"
  • sequence creates for "each element of nvec the sequence seq_len(nvec[i])"
  • logical values are automatically coerced to 0/1 when multiplied with numbers

All these functions together:

sequence(rle(ind)$lengths) * ind
#[1] 1 0 1 2 0 0 0 1 2 3 0
Roland
  • 127,288
  • 10
  • 191
  • 288