Dominique
Dominique

Reputation: 1

How to count values between zero in R?

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

Answers (3)

ThomasIsCoding
ThomasIsCoding

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

akrun
akrun

Reputation: 887108

Using rleid

library(data.table)
table(rleid(v != 0)[v != 0])

Upvotes: 1

Ronak Shah
Ronak Shah

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

Related Questions