Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 531
Carey Avatar asked Apr 12 '11 00:04

Carey


People also ask

How do I check if a number is negative in R?

Definition: The sign R function returns the signs of numeric elements. The value 1 is returned for positive numbers, the value 0 is returned for zero, and the value -1 is returned for negative numbers. Basic R Syntax: You can find the basic R programming syntax of the sign function below.

How do you get rid of a negative number in a vector?

The recommended way is to use the remove_if and erase pattern. Note that std::vector has two versions of erase(). The one used in this thread takes two arguments and removes a range of elements. There is also a single-argument version that removes one element.


1 Answers

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).

like image 81
Dirk Eddelbuettel Avatar answered Oct 19 '22 20:10

Dirk Eddelbuettel