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.
Aucun commentaire:
Enregistrer un commentaire