Home Ask Login Register

Developers Planet

Your answer is one click away!

lp1585 February 2016

How to count the number of 0s between 1s in R?

I have some precipitation data that I converted into binary, where 1 = a precipitation event and 0 = no precipitation. The data set has over 35,000 values, but here is an example of what my data would look like this:

x = 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1.

I would like to count the number of consecutive days without an event, so my output would look like this:

y = 2, 3, 6, 2.

I have tried to use the help site but none of the suggested solutions worked.

Answers


akrun February 2016

We can use rle

with(rle(x), lengths[!values])
#[1] 2 3 6 2

If we have '0's at the end of the vector, we can start the count from the first 1 to the last 1

x1 <- x[Reduce(':',as.list(range(which(x==1))))]
with(rle(x1), lengths[!values]) 


Stibu February 2016

This is a somewhat convoluted solution (but I think it's fun):

diff(c(0, cumsum(!x)[diff(x) == 1]))

diff(x) == 1 gives TRUE for each last zero before a one. cumsum(!x) gives you a vector that contains as element i the number of zeros that are contained in x up to and including x[i]. Finally, you need diff() again, because you only want the number of zeros since the last one.

The solution works with leading zeroes, but fails with zeroes at the end. It can be adapted to also adapt the latter case by making sure that the last number is always a one:

y <- c(0, 0, 0, x, 0, 0, 0, 0)
diff(c(0, cumsum(!c(y,1))[diff(c(y,1)) == 1]))

Post Status

Asked in February 2016
Viewed 1,176 times
Voted 5
Answered 2 times

Search




Leave an answer


Quote of the day: live life