简体   繁体   中英

Using replicate over for loop

I want to make a simulation 10000 times on the difference between load and demand. I need the proportion of negative differences over all simulation. I used the for loop below, but this is not performant for large simulations as it requires me to calculate everything by hand later on.

How can I do the same with replicate? What are the benefits of using replicate over for loop?

 for(i in 1:10){
 load<-rnorm(10,8,2)
 demand<-c(6,7,6,5,6,7,8,7,6,5)
 diff<-load-demand
 res<-sum(diff<0) / 10# sum the negative differences
 print(res)
 }

The big disadvantage of using a for-loop, is that you don't automatically store everything in an object. replicate() does that for you.

Another tip: keep everything that doesn't change out of the loop (like the definition of demand )

How to do what you describe using replicate() :

nsim <- 10000
demand <- c(6,7,6,5,6,7,8,7,6,5)
res <- replicate(nsim,{
  load <- rnorm(10,8,2)
  diff <- load - demand
  return(sum(diff < 0))
})
res <- sum(res) / nsim

The return() function isn't necessary (a code block returns the last line it executes), but I add it so you see immediately what's going to be stored in res .

But you actually don't need a loop to do this (given you described what you want accurately). You can just use vectorization and recycling to do this:

nsim <- 10000
demand <- c(6,7,6,5,6,7,8,7,6,5)
load <- rnorm(10*nsim, 8, 2)
diff <- load - demand
res <- sum(diff < 0) / nsim

replicate or a for loop actually only make sense if you want to keep the results for each simulation. As you're only interested in the overall result, the second code block will be more performant and R-like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM