alex46015
2010-Mar-17 20:02 UTC
[R] How to use "ifelse" to generate random value from a distribution
I need use different parameters of distribution for different case to generate random value, but I use ifelse, the generated value is fixed without change. Here is example data1 y x 1 1 2 2 2 1 3 3 2 4 4 3 5 5 3 6 6 1 7 7 2 8 8 1 9 9 1 10 10 3 11 11 3 12 12 2 ifelse(data1$x==1,rnorm(1,2,1),ifelse(data1$x==2,rnorm(1,-2,1),rnorm(1,110,1))) [1] -1.8042172 0.8478681 -1.8042172 110.0301239 110.0301239 0.8478681 -1.8042172 0.8478681 0.8478681 110.0301239 [11] 110.0301239 -1.8042172 How can I get real random value from a distribution. Thanks. -- View this message in context: http://n4.nabble.com/How-to-use-ifelse-to-generate-random-value-from-a-distribution-tp1597064p1597064.html Sent from the R help mailing list archive at Nabble.com.
alex46015
2010-Mar-17 20:25 UTC
[R] How to use "ifelse" to generate random value from a distribution
I think I figure it out. ifelse(data1$x==1,rnorm(12,2,1),ifelse(data1$x==2,rnorm(12,-2,1),rnorm(12,110,1))) Please correct me if I am wrong. Thanks -- View this message in context: http://n4.nabble.com/How-to-use-ifelse-to-generate-random-value-from-a-distribution-tp1597064p1597102.html Sent from the R help mailing list archive at Nabble.com.
Erik Iverson
2010-Mar-17 20:51 UTC
[R] How to use "ifelse" to generate random value from a distribution
alex46015 wrote:> I think I figure it out. > > ifelse(data1$x==1,rnorm(12,2,1),ifelse(data1$x==2,rnorm(12,-2,1),rnorm(12,110,1))) >Where is the number 12 coming from? Is that the length of data1$x? Here is a sample using the fact that rnorm can accept vectors of means and sds. My x is randomly generated since you did not provide a reproducible example. #random data, can take on 3 values x <- sample(1:3, 100, replace = TRUE) #i tried to make this identical to your criteria mns <- ifelse(x == 1, 2, ifelse(x==2, -2, 110)) #use vectors!, do not hardcode length(x)! rnorm(length(x), mns) HTH, --Erik