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

r
40,429

Solution 1

You want to read 'An Introduction to R'. Your answer here is simply

 sum(  x < 0  )

which works thanks to vectorisation. The x < 0 expression returns a vector of booleans over which sum() can operate (by converting the booleans to standard 0/1 values).

Solution 2

There is a good answer to this question from Steve Lianoglou How to identify the rows in my dataframe with a negative value in any column?

Let me just replicate his code with one small addition (4th point).

  1. Imagine you had a data.frame like this:

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

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

    which(has.neg)
    
  4. Here is a count of elements with negative numbers:

    length(which(has.neg))
    
Share:
40,429

Related videos on Youtube

Carey
Author by

Carey

Updated on November 01, 2020

Comments

  • Carey
    Carey over 3 years

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

  • Matthew Lundberg
    Matthew Lundberg over 11 years
    The vector is not converted to numeric (for later versions of R anyway) - sum works on logical directly. This can be easily observed. x <- rep(c(T,F), 2^30-1) causes my R session RSS to increase to ~8G. sum(x) does not increase this. However, sum(as.numeric(x)) causes the RSS to increase to ~25G (and of course returns the same value).
  • Jeffrey Evans
    Jeffrey Evans over 6 years
    The OP has a vector so, something like length(x[x < 0]) would work.
  • Andrii
    Andrii over 6 years
    If data set has NA values the command should be sum(x < 0, na.rm = TRUE). Otherwise it returns NA as a result