Edward Lin
Edward Lin

Reputation: 609

how to use function & ifelse() to sum up the total of negative values?

I wrote a simple function to hopefully calculate the total of negative values but failed. Ideally, when I passed a vector into the function, it should give the total count of negative values. Can anyone help, please?

My code:

    arg <- c(rnorm(50, 0))
    neg <- 0
    count.negative.fun <- function(x) {
            ifelse(x <= 0, neg = neg +1,)
            return(neg)
     }

When I called:

  count.negative.fun(arg)

It gives me this error message: "Error in ifelse(x <= 0, neg = neg + 1, ) : unused argument (neg = neg + 1)"

Upvotes: 2

Views: 981

Answers (2)

MKR
MKR

Reputation: 20095

Another possible way is by using length function itself. As:

length(arg[arg<0])
#[1] 26

Upvotes: 1

Julius Vainora
Julius Vainora

Reputation: 48211

When using ifelse and defining a function, one might do

count.negative.fun <- function(x) sum(ifelse(x <= 0, 1, 0))
count.negative.fun(arg)
# [1] 26

See ?ifelse. It returns 1 for those cases when an element of x is nonpositive and 0 otherwise. Then we may sum the result.

However, you may also simply write

sum(arg < 0)
# [1] 26

Upvotes: 2

Related Questions