[R] ifelse question
Tony Plate
tplate at blackmesacapital.com
Tue Dec 12 22:17:57 CET 2006
I think you can find your answer if you study this part of the
documentation for ifelse:
Details:
If yes or no are too short, their elements are recycled. yes will be
evaluated if and only if any element of test is true, and analogously
for no.
Also, consider this call:
ifelse(1:12 > 5, 1:3, 11:14)
-- Tony Plate
Jacques Ropers wrote:
>>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.
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list