简体   繁体   English

在R中建立ifelse循环的最快方法

[英]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 生成介于0和1之间的Randon数

     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 根据生成的randon数,我将值1,2,3,4或5分配给变量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. 我将这个模拟重复了1000次,我觉得使用ifelse并不是实现这一目标的最佳方法。 Is there a way to avoid the ifelse loop and improve performance of this part of the code ? 有没有办法避免ifelse循环并提高这部分代码的性能?

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. 如果有人对我有兴趣,我有完整的代码( https://quant.stackexchange.com/questions/12868/kelly-capital-growth-investment-strategy-example-in-r )完整的代码。

I upvoted josilber's answers because I think it is very good. 我赞成josilber的答案,因为我认为这非常好。 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: 您可以通过以下sample使用sample获得相同的结果:

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 . 似乎sample.int甚至更快,并且比josilber的version2快16.9倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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