简体   繁体   中英

Fastest Way to build this ifelse loop in R

What i am trying to do is :

  1. Generate a Randon Number between 0 and 1

     rand_number <- runif(1,0,1) 
  2. Depending on the randon number generated i atribute the value 1,2,3,4 or 5 to the variable bet_choice

     bet_choice <- ifelse(rand_number<0.1,1, ifelse(rand_number>0.1 & rand_number<=0.4,2, ifelse(rand_number>0.4 & rand_number<=0.7,3, ifelse(rand_number>0.7 & rand_number<=0.9,4,5)))) 

I am repeating this simulation 1000 times and i feel that using ifelse is not the optimal way to reah this goal. Is there a way to avoid the ifelse loop and improve performance of this part of the code ?

I have the complete code on what i am trying to do in ( https://quant.stackexchange.com/questions/12868/kelly-capital-growth-investment-strategy-example-in-r ) in case someone is interested in the complete code.

I upvoted josilber's answers because I think it is very good. But I'd just add that you're really sampling from a particular discrete distribution where you use the uniform random variable to select the random number with the correct probabilities. You can use sample to get the same results with the following:

s <- sample(1:5, size = 1000, replace = TRUE, prob = c(0.1, 0.3, 0.3, 0.2, 0.1))

You can test it yourself, but I believe this should be even faster.

edit I've now tested it with the following:

library(microbenchmark)
s1 <- function() sample(1:5, size = 1000, replace = TRUE, prob = c(.1,.3,.3,.2,.1))
s2 <- function() sample.int(5, size = 1000, replace = TRUE, prob = c(.1,.3,.3,.2,.1))
microbenchmark(s1(), s2())
#Unit: microseconds
# expr    min     lq median     uq    max neval
# s1() 39.389 40.536 41.300 41.683 76.483   100
# s2() 29.828 30.594 31.358 31.741 43.213   100

It seems that sample.int is even faster and yield a 16.9x speed up from josilber's version2 .

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