2009/10/6 Uwe Ligges <lig...@statistik.tu-dortmund.de>: > > > Gabor Grothendieck wrote: >> >> 2009/10/6 Uwe Ligges <lig...@statistik.tu-dortmund.de>: >>> >>> The first rule is easy: As long as you are using scalar valued (i.e. >>> length >>> 1 vectors in R) "cond", you should prefer >>> if(cond) cons.expr else alt.expr >>> rather than >>> ifelse(cond, yes, no) >>> because the latter one evaluates both "yes" and "no" while the former one >>> evaluates exactly one of both expressions. >> >> I don't think that that is true. The false leg was not evaluated here: >> >>> ifelse(TRUE, { cat("a"); 1}, {cat("b"); 2}) >> >> a[1] 1 > > > Ah, indeed that changed at some point and I forgot that the code checks for > the length of cond nowadays. Thanks for pointing it out. >
Modulo NAs, I think it checks whether cond is all TRUEs or all FALSEs and in either of those cases it only evaluates one or the other. Of course if cond is length 1 then it necessary is all TRUE or all FALSE. If its a mixture of TRUE and FALSE then it evaluates both. > ifelse(c(TRUE, TRUE), { cat("a"); 1}, {cat("b"); 2}) a[1] 1 1 > ifelse(c(FALSE, FALSE), { cat("a"); 1}, {cat("b"); 2}) b[1] 2 2 > ifelse(c(TRUE, FALSE), { cat("a"); 1}, {cat("b"); 2}) ab[1] 1 2 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.