I have the following problem. I want to count the number of occurrences of values that are smaller or equal to zero. Example in the following data I have 3 occurrences 1(0,0,0),2(-1,-2),3(0,0). Is there any build in function in R to count the successive occurrences.
a <- c(2,4,5,3,2,4,7,0,0,0,4,3,2,-1,-2,3,2,0,0,4)
If you want to count the number of runs with values below zero:
sum(rle(a <= 0)$values)
which gives:
[1] 3
How this works:
rle
function you create a runlength-encoding of a <= 0
.The output of rle(a <= 0)
is:
Run Length Encoding
lengths: int [1:7] 7 3 3 2 2 2 1
values : logi [1:7] FALSE TRUE FALSE TRUE FALSE TRUE ...
Now you just have to sum the values part of the rle
-object:
> sum(rle(a <= 0)$values)
[1] 3
You can use rle
:
> sum(rle(a<=0)$values)
[1] 3
Explanation:
rle
breaks the vector into runs which are > 0 or <= 0. The $values
are either true
or false
depending on whether or not the corresponding run satisfies the predicate (a <= 0
) or its negation. You want the runs corresponding to the value TRUE
, the function sum
coerces those TRUE
s to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With