[R] evaluation of the alternative expression in ifelse

Dimitrios Rizopoulos Dimitris.Rizopoulos at med.kuleuven.be
Sun Jun 4 20:15:37 CEST 2006


Quoting Renaud Lancelot <renaud.lancelot at gmail.com>:

> Dear all,
> 
> I am trying to avoid the warnings produced by:
> 
> > x <- -2:2
> > log(x)
> [1]       NaN       NaN      -Inf 0.0000000 0.6931472
> Warning message:
> production de NaN in: log(x)
> 
> I thought that using ifelse would be a solution, but it is not the
> case:
> 
> > ifelse(test = x < 0, yes = NaN, no = log(x))
> [1]       NaN       NaN      -Inf 0.0000000 0.6931472
> Warning message:
> production de NaN in: log(x)
> 
> I am aware of the section "Warning" of the help page for ifelse:
> Sometimes it is better to use a construction such as (tmp <- yes;
> tmp[!test] <- no[!test]; tmp), possibly extended to handle missing
> values in test.
> 
> However, is there a way to avoid the evaluation of the alternative
> expression in ifelse when the argument test is false ?

I think the answer is no; the Details section of ifelse() reads: 

"... 'yes' will be evaluated if and only if *any* element of test is 
true, and analogously for 'no'." 

check also the code behind ifelse(). If you really want to use ifelse
(), then you could consider something like:

x <- -2:2
opt <- options(warn = -1)
ifelse(test = x < 0, yes = NaN, no = log(x))
options(opt)


I hope it helps.

Best,
Dimitris


> Best regards,
> 
> Renaud
> -- 
> Renaud LANCELOT
> Département Elevage et Médecine Vétérinaire (EMVT) du CIRAD
> Directeur adjoint chargé des affaires scientifiques
> 
> CIRAD, Animal Production and Veterinary Medicine Department
> Deputy director for scientific affairs
> 
> Campus international de Baillarguet
> TA 30 / B (Bât. B, Bur. 214)
> 34398 Montpellier Cedex 5 - France
> Tél   +33 (0)4 67 59 37 17
> Secr. +33 (0)4 67 59 39 04
> Fax   +33 (0)4 67 59 37 95
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
> 
> 


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



More information about the R-help mailing list