[R] help on setting boundaries for generating random numbers

peter dalgaard pdalgd at gmail.com
Sat Sep 1 19:33:08 CEST 2012


On Sep 1, 2012, at 19:20 , Petr Savicky wrote:

> On Sat, Sep 01, 2012 at 02:29:40AM -0700, Andras Farkas wrote:
>> Dear All,
>> ?
>> is there a way to set low and high limits to a simulation with rlnorm()? 
>> ?
>> as an example:
>> ?a <-rlnorm(500,0.7,1)
>> ?
>> ?
>> I get the summary of
>> ?
>> Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
> 0.1175  1.0590  2.1270  3.4870  4.0260 45.3800   
>> 
>> I would like to set limits so that the simulated values minimum would be greater then 0.5 and maximum of less than 30. If during simulation a value?outside of the limits would be simulated, then I would like R to "throw that value out" and go back to generate another random number instead that would fit the limits criteria. 
> 
> Hi.
> 
> If you want to generate one number at a time, try this
> 
>  while (1) {
>      a <- rlnorm(1, 0.7, 1)
>      if (0.5 < a && a < 30) break
>  }
> 
> If you want to generate a vector and avoid a loop over its components,
> try something like the following
> 
>  n <- 500
>  while (1) {
>      a <- rlnorm(2*n, 0.7, 1)
>      a <- a[0.5 < a & a < 30] # only one & here
>      if (length(a) >= n) break
>  }
>  a <- a[1:n]
> 
> Hope this helps.

It's easier to use the inverse distribution function method:

n <- 500
u <- plnorm(30, .7, 1)
l <- plnorm(.5, .7, 1)
a <- qlnorm(runif(n, l, u), .7, 1)
summary(a)
hist(log(a))

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com




More information about the R-help mailing list