Meems
Meems

Reputation: 101

How to convert this for loop into an apply function?

I'm quite new to R and am currently studying a Monte Carlo Simulation example I found online, however it is given in a for loop. I would like to move away from these but am struggling to convert it into an apply function. Any help would be appreciated:

for (k in 1:1000)
    {
       rolls = runif(1,3000,5000)
       bags = runif(1,2000,4000)
       cases = runif(1,150,200)*30
       total = min (rolls, bags, cases)
       results = rbind(results, data.frame(rolls, bags, cases, total))
     }

Upvotes: 0

Views: 69

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389275

You don't need for loop, nor any apply function.

runif can generate multiple n numbers in one go. To get rowwise minimum you can use pmin.

n <- 1000
rolls = runif(n,3000,5000)
bags = runif(n,2000,4000)
cases = runif(n,150,200)*30
total = pmin(rolls, bags, cases)
results <- data.frame(rolls, bags, cases, total)

As @Roland points out for a general case where you can't vectorize the simulation you can use replicate function.

simulation <- function() {
    rolls = runif(1,3000,5000)
    bags = runif(1,2000,4000)
    cases = runif(1,150,200)*30
    total = min(rolls, bags, cases)
    data.frame(rolls, bags, cases, total)
}

results <- t(replicate(1000, simulation(), simplify = TRUE))

Upvotes: 2

Related Questions