1

Is there an efficient way to calculate the length of portions of a vector that repeat a specified value? For instance, I want to calculate the length of rainless periods along a vector of daily rainfall values:

daily_rainfall=c(15, 2, 0, 0, 0, 3, 3, 0, 0, 10)

Besides using the obvious but clunky approach of looping through the vector, what cleaner way can I get to the desired answer of

rainless_period_length=c(3, 2)

given the vector above?

r2evans
  • 141,215
  • 6
  • 77
  • 149
Lucas Fortini
  • 2,420
  • 15
  • 26
  • 3
    Our old friend `?rle` is what you are looking for - run-length-encoding - very close to a possible duplicate of https://stackoverflow.com/questions/42936958/get-length-of-runs-of-missing-values-in-vector – thelatemail Dec 06 '18 at 22:29

1 Answers1

6

R has a built-in function rle: "run-length encoding":

daily_rainfall <- c(15, 2, 0, 0, 0, 3, 3, 0, 0, 10)

runs <- rle(daily_rainfall)
rainless_period_length <- runs$lengths[runs$values == 0]

rainless_period_length

output:

[1] 3 2
Jack Brookes
  • 3,720
  • 2
  • 11
  • 22