Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count zeroes between two non-zero number and then continue doing this through the array of numbers in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the precipitation dataset I am dealing with:
precipitation data

I want to count the number of days between precipitation events. Maybe this will make the question clearer.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading