Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ifelse in R when one of the options produces NAs?

I want to vectorize a function that relies on checking a condition and depending on whether this condition is TRUE or FALSE, return the outcome of one of two functions, respectively. The problem is that, when the condition is FALSE, the first function cannot be evaluated. Then, ifelse returns the correct values but it also produces a warning. I would like to produce a function that does not produce warnings.

I have tried ifelse(), but it does not work. I was expecting that this command would skip the evaluation of the first function when the condition is FALSE.

Here is an illustrative piece of R code

p = c(-1,1,-1,1,-1,-1,-1,1)

ifelse(p>0, sqrt(p), p^2)

which returns

[1] 1 1 1 1 1 1 1 1
Warning message:
In sqrt(p) : NaNs produced

As you can see, the outcome is correct but, for some reason, it evaluates the function at the first function when condition is FALSE. Thus, I would like to somehow avoid this issue.

like image 408
Snoop Dogg Avatar asked Dec 22 '25 00:12

Snoop Dogg


1 Answers

We can create a numeric vector and then fill the elements based on the condition put forward by 'p'

out <- numeric(length(p))
out[p > 0] <- sqrt(p[p > 0])
out[p <= 0] <- p[p <= 0]^2

With ifelse we need to have all arguments of the same length. According to ?ifelse

ifelse(test, yes, no)

A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no

What happens is that we do both the calculations on the entire vector and replace the values of 'p' based on the test condition. For sqrt, the negative values definitely gives warning and output as NaN. While the NaN elements don't show up in the output, the warning was already printed. The warning is a friendly one, but can be suppressed with suppressWarnings

like image 157
akrun Avatar answered Dec 24 '25 14:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!