[R] ifelse question

Jacques Ropers jropers at gmail.com
Tue Dec 12 22:11:04 CET 2006


> But you got only two (eventually one) distinct values, right? Look at
> the code for 'ifelse': yes and no are only called once each, then
> recycled to desired length.
>
> I guess you want something like
>
> x <- rnorm(10)
> y <- rnorm(10)
> z <- rnorm(10)
> y1 <- ifelse(x > 0, y, z)
>   
Thanks for the help.

Although this would do the trick, is there a way to call repetitively 
rnorm (rpois...) *inside the ifelse* rather than constructing the vector 
outside ? Like in the following where cos() and sin() functions are 
evaluated for each row :
x <- rnorm(10)
y1 <- ifelse(x > 0, cos(x), sin(x))

I am trying to understand the difference of behaviour. R acts as if 
rnorm(1) return value were known after the first call and does not 
evaluate rnorm(1) in

y1 <- ifelse(x > 0, rnorm(1) ,  rnorm(1))

again after the first evaluation.


Jacques.



More information about the R-help mailing list