Reputation: 1
I have something like this:
v <- c(0, 0, 0.05, 1, 3, 0, 0, 0, 0, 10, 2, 4, 0.8, 0, 0)
I need to count the number of elements between zero values, so i will get: 3, 4
First time posting here.. thanks!
Upvotes: 0
Views: 75
Reputation: 101335
Here is another base R option without using rle
> z <- which(v != 0)
> tapply(z, cumsum(diff(c(0, z)) != 1), length)
1 2
3 4
or
> attr(gregexpr("1+", paste0(+!!v, collapse = ""))[[1]], "match.length")
[1] 3 4
Upvotes: 0
Reputation: 388982
We can use rle
:
v <- c(0, 0, 0.05, 1, 3, 0, 0, 0, 0, 10, 2, 4, 0.8, 0, 0)
with(rle(v != 0), lengths[values])
#[1] 3 4
Upvotes: 4