[R] ifelse question
Göran Broström
goran.brostrom at gmail.com
Tue Dec 12 21:46:46 CET 2006
On 12/12/06, Leeds, Mark (IED) <Mark.Leeds at morganstanley.com> wrote:
> ifelse is vectorized but there is no way you could know what's
> happening with that command
> because you have rnorm(1) for both conditions. I think you mean to have
> something different in one of them ?
>
> Whewn I run your code in my R session, I get 10 values for y1, so there
> isn't anything wrong except
> That you have the same statement for both cases.
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)
but this whole business is probabilistically the same as
x <- rnorm(10)
y1 <- rnorm(10)
which of course is faster and more transparent.
Göran
>
>
>
>
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of
> jropers at freesurf.fr
> Sent: Tuesday, December 12, 2006 3:13 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] ifelse question
>
> Dear R-helpers,
> How come that in the following code the rnorm() function is evaluated
> only once for each branch of the 'ifelse' ?
>
> x <- rnorm(10)
> y1 <- ifelse(x > 0, rnorm(1) , rnorm(1))
>
>
> What is the right way to make it called/evaluated for each row, apart
> from a 'for' loop ?
>
> Thanks,
>
> 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.
> --------------------------------------------------------
>
> This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}
>
> ______________________________________________
> 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.
>
--
Göran Broström
More information about the R-help
mailing list