mardi 28 juillet 2015

Using ifelse with random variate generation in a function applied to a vector

I want to create a function that generates a random number based on its input and apply it to a boolean vector.

f <- function(x, p) ifelse(x, runif(1)^p, runif(1)^(1/p))
f(c(T,T,T,F,F,F), 2)   

What I get is not what I wanted.

[1] 0.0054 0.0054 0.0054 0.8278 0.8278 0.8278

I'd expect a new random number for every element of my input vector, not two random numbers repeated. Why do I get this result, and how can I get the desired result which would be the same as

c(runif(3)^2, runif(3)^(1/2))

which yields a new random number for every element

0.0774 0.7071 0.2184 0.8719 0.9990 0.8819




Aucun commentaire:

Enregistrer un commentaire