Skip to content
Prev 258083 / 398502 Next

density plot of simulated exponential distributed data

Hi:

Try this (and note the use of vectorization rather than a loop):

rate <- 3
dta <- -log(1 - runif(1000))/rate
hist(dta, nclass = 30, probability = TRUE)
x <- c(0.001, seq(0, 3, by = 0.01))
lines(x, dexp(x, rate = 3))

This is the difference in timings between the vectorized and iterative
methods of generating the samples:
user  system elapsed
   0.10    0.00    0.09
+ i <- 1
+ for(i in 1:1000){
+         r <- runif(1)
+         dt[i] <- log(1-r)/(-rate)
+         i <- i+1
+  } }))
   user  system elapsed
   9.35    0.00    9.40

Vectorization is usually your friend in R, and it pays to use it when
available. All of the d*, p*, q* and r* functions, where * denotes the
suffix for a distribution, are vectorized, as are most of the
functions in base R. A happy by-product is that it also makes for more
easily readable code.

HTH,
Dennis
On Tue, Apr 26, 2011 at 3:19 PM, Juanjuan Chai <chaij at umail.iu.edu> wrote: