Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of occurrences

Tags:

r

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)
like image 795
kelamahim Avatar asked Feb 26 '17 15:02

kelamahim


2 Answers

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:

  • With the 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
    
like image 102
Jaap Avatar answered Sep 21 '22 17:09

Jaap


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 TRUEs to 1.

like image 40
John Coleman Avatar answered Sep 19 '22 17:09

John Coleman