disclaimer: this code is bad practice. and only works because of something like . Never use it in a real situation. This question concerns the interesting behavior of R, nothing like this.
After reading this question, I was puzzled. Apparently ifelse can access information that should be hidden.
Let's say we do:
> x <- expression(dd <- 1:3) > y <- expression(dd <- 4:6) > z <- c(1,0) > eval(x) > eval(y) >
We do not get a way out. Logic, since both expressions are actually a dd vector. eval () should not give a result then. But oddly enough, when you try funny code
> ifelse(z==0,eval(x),eval(y)) [1] 4 2
Do you get a way out ??? Does anyone have an explanation?
It is not as simple as "R evaluates and then uses dd." Whatever order you specify, whatever condition you use, dd is always the last mentioned eval() .
> ifelse(z==0,eval(x),eval(y)) > dd [1] 4 5 6 > ifelse(z==1,eval(x),eval(y)) > dd [1] 4 5 6 > z <- c(0,1) > ifelse(z==0,eval(x),eval(y)) > dd [1] 4 5 6 > ifelse(z==1,eval(x),eval(y)) > dd [1] 4 5 6 > ifelse(z==1,eval(y),eval(x)) > dd [1] 1 2 3
EDIT:
a closer look at the ifelse source code reveals that the line, making sure this happens, is rep() :
> x <- expression(dd <- 1:3) > eval(x) > rep(eval(x),2) [1] 1 2 3 1 2 3
However, this does not solve the issue ...