2

I am looking to count the number of times the value is below a point and when it exceeds the threshold to start counting from start.

For example if I have X <- c(1,2,11,14,5,6,7,12) and I am counting the number of times the values are less than 10 consecutively then I want an answer as

Output = 2,3 Since 1,2 are less than 10 so total 2 and then the count starts again for 5,6,7 and the total is 3

pogibas
  • 27,303
  • 19
  • 84
  • 117
Sunichie
  • 25
  • 4

1 Answers1

4

You can use rle function :

with(rle(X < 10),lengths[values])
> [1] 2 3

Brief explanation :

1) X < 10 returns : c(TRUE,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE,FALSE) so we just need to count batches of consecutive TRUE's

2) rle(X < 10) does exactly that, returning an object (a list with lengths and values properties) indicating the consecutive batches of values and their length. In this case :

Run Length Encoding
  lengths: int [1:4] 2 2 3 1
  values : logi [1:4] TRUE FALSE TRUE FALSE

3) So doing RLE <- rle(X < 10); RLE$lengths[RLE$values] we got exactly what you want, but creating a useless temporary variable RLE (not a big deal, actually), but using with we just skip that passage.

digEmAll
  • 56,430
  • 9
  • 115
  • 140