On Feb 15, 2010, at 11:01 AM, hadley wickham wrote:

I, personally, utilize the ifelse(test,statement,statement) function when possible over the methodology outlined.

if + else and ifelse perform quite different tasks, and in general can
not (and should not) be exchanged.  In particular, note that for
ifelse, "the class attribute of the result is taken from ‘test’ and
may be inappropriate for the values selected from ‘yes’ and  'no’".

I have always been puzzled by that bit of advice/knowledge on the help page. "test" will of necessity be of class "logical", and yet I regularly succeed in producing numeric and character vectors with ifelse. In fact ifelse would be rather limited in utility if it only returned logical vectors.

> test1 <- 1:10 > 5
> yes1 <- letters[1:10]
> no1 <- LETTERS[1:10]
> ifelse(test1, yes1, no1)
 [1] "A" "B" "C" "D" "E" "f" "g" "h" "i" "j"
> class( ifelse(test1, yes1, no1) )
[1] "character"

Further newbie query: I thought I had read there was also a performance "gotcha" in that one of those constructs evaluated both the affirmative and negative consequents, but it appears from the help page that ifelse does not have that effect. And although that question is not addressed in the ?Control help page, testing makes me think it is also not true of if() {}else{}:

if (1) {print("x")} else{print("y")}
[1] "x"
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT

______________________________________________
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.

Reply via email to