Lets say we have this following data:
a <- c(0.1,0.2,0,0,0,0,1.2,1.4,0,0,1.4)
b <- c(0,0,0,1.1,0,0,0,0,0.25,0.51,0)
Now I would like to count the zeroes between two non-zero numbers and continue the count in consequent non-zero numbers. So, the output would look like for a it would be an array of (4,2) for b it would be an array of (3,4,1)
I tried counting zeroes with general filtering codes, but I can't replicate the code for the consequent non-zero-zero numbers.
Here is the precipitation dataset I am dealing with:
I want to count the number of days between precipitation events. Maybe this will make the question clearer.
CodePudding user response:
You can use run-length encoding (rle
):
a <- c(0.1,0.2,0,0,0,0,1.2,1.4,0,0,1.4)
b <- c(0,0,0,1.1,0,0,0,0,0.25,0.51,0)
with(unclass(rle(a)), lengths[values == 0])
#> [1] 4 2
with(unclass(rle(b)), lengths[values == 0])
#> [1] 3 4 1
Created on 2022-10-26 with reprex v2.0.2