An elegant way to count the number of negative elements in a vector?

I have a data vector with 1024 values ​​and need to count the number of negative records. Is there an elegant way to do this without looping and checking if the element is <0 and incrementing the counter?

+6
source share
2 answers

You want to read "Introduction to R". Your answer here is simple.

sum( x < 0 ) 

which works thanks to vectorization. The expression x < 0 returns a vector of Boolean elements that sum() can work on (by converting Boolean values ​​to standard 0/1 values).

+27
source

There is a good answer to this question from Steve Lyanoglow. How can I identify rows in my data core with a negative value in any column?

Let me just repeat his code with one small addition (4th paragraph).

  • Imagine you had a data.frame file:

     df <- data.frame(a = 1:10, b = c(1:3,-4, 5:10), c = c(-1, 2:10)) 
  • This will return you a logical vector whose rows have negative values:

     has.neg <- apply(df, 1, function(row) any(row < 0)) 
  • Here are the indices for negative numbers:

     which(has.neg) 
  • Here is the number of elements with negative numbers:

     length(which(has.neg)) 
0
source

Source: https://habr.com/ru/post/885690/


All Articles