[R] random value generation with added constraint.

Duncan Murdoch murdoch.duncan at gmail.com
Thu Aug 4 22:21:14 CEST 2011


On 04/08/2011 12:03 PM, Vijayan Padmanabhan wrote:
> Hi
> I am looking at generating a random dataset of say 100 values fitting in a
> normal distribution of a given mean and SD, I am aware of rnorm
> function. However i am trying to build into this function one added
> constraint that all the random value generated should also obey the
> constraint that they only take values between say X to X+25
> How do i do this in R?

The easiest way is to use the inverse-CDF method to generate values.  
For example:

mu <- 50
sd <- 10
X <- 30
lower <- pnorm(X, mean=mu, sd=sd)
upper <- pnorm(X+25, mean=mu, sd=sd)
U <- runif(1000, lower, upper)
Y <- qnorm(U, mean=mu, sd=sd)


This will fail if you go too far out in the tail (e.g. trying mu=0, 
sd=1, X=30); for that you need to be more careful, and work with log 
probabilities, etc.

Duncan Murdoch


> Any help would be highly appreciated,.
> Thanks
> Vijayan Padmanabhan
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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