r - Optimise code for a simple monte carlo like simulation -


i run following code works take ages , i'm sure there way same results faster.

runs <- 1000 prediction <- runif(77,0,1) n< - length(prediction) df.all <- data.frame(preds = rep(prediction, runs),                      simno=rep(1:runs,each=n))  (x in 1:runs) {   (i in 1:length(df.all$preds)){     df.all$rand[i] <- sample(1:100,1)     df.all$win[i] <- ifelse(df.all$rand[i]<df.all$preds[i]*100,1,0)   } }  df.all% >% group_by(simno) %>% summarise(wins=sum(win)) -> output 

this can vectorise by:

  • performing single sample operation (not additional replace = true argument.
  • performing single comparison >

you can remove inner loop get

for (x in 1:runs) {   df.all$rand = sample(1:100, size = length(prediction), replace=true)   df.all$win = df.all$rand < df.all$preds*100 } 

you can take 1 step further , remove loop

df.all$rand = sample(1:100, n = nrow(df.all), replace=true) df.all$win = df.all$rand < df.all$preds*100 

Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -