[R] help on setting boundaries for generating random numbers

Petr Savicky savicky at cs.cas.cz
Sat Sep 1 19:20:23 CEST 2012


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.

Petr Savicky.




More information about the R-help mailing list