vendredi 15 avril 2016

Generate random numbers without loops

I'm trying to reduce as much as I can the execution time of a function that sums the output of a sequence of Bernoulli trials.

This is my working-but-slow approach:

set.seed(28100)
sim <- data.frame(result = rep(NA, 10))
for (i in 1:nrow(sim)) {
  sim$result[i] <- sum(rbinom(1200, size = 1, prob = 0.2))
}
sim
# result
# 1     268
# 2     230
# 3     223
# 4     242
# 5     224
# 6     218
# 7     237
# 8     254
# 9     227
# 10    247

How could I obtain the same result without a for-loop?

I tried this...

set.seed(28100)
sim <- data.frame(result = rep(sum(rbinom(1200, size = 1, prob = 0.2)), 10))
sim
# result
# 1     269
# 2     269
# 3     269
# 4     269
# 5     269
# 6     269
# 7     269
# 8     269
# 9     269
# 10    269

But clearly the argument of rep() is executed only once.




Aucun commentaire:

Enregistrer un commentaire