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