[R] How to use "ifelse" to generate random value from a distribution

Erik Iverson eriki at ccbr.umn.edu
Wed Mar 17 21:51:17 CET 2010



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



More information about the R-help mailing list