以给定的概率生成随机数 [英] Generate random number with given probability
问题描述
我有一个问题,基本上是以下matlab问题的矢量化R解决方案:
I have a question which is basically the vectorized R solution to the following matlab problem:
我能够通过以下方式生成随机事件结果:随机统一编号和每个事件的给定概率(总和为100%-可能仅发生一个事件):
I'm able to generate the random event outcome based on random uniform number and the given probability for each single event (summing to 100% - only one event may happen) by:
sum(runif(1,0,1) >= cumsum(wdOff))
但是该函数仅采用一个随机的统一编号,而我希望它采用一个随机的统一编号的向量并为这些条目输出相应的事件.
However the function only takes a single random uniform number, whereas I want it to take a vector of random uniform numbers and output the corresponding events for these entries.
所以基本上我正在寻找Matlab中Oleg的矢量化解决方案的R解决方案(从注释到matlab解决方案):
So basically I'm looking for the R solution to Oleg's vectorized solution in matlab (from the comments to the matlab solution):
向量化解决方案:sum(bsxfun(@ge, r, cumsum([0, prob]),2)
其中r
是列向量,而prob
是行向量.– Oleg"
"Vectorized solution: sum(bsxfun(@ge, r, cumsum([0, prob]),2)
where r
is a column vector and prob
a row vector. – Oleg"
如果需要更多信息,请告诉我.
Tell me if you need more information.
推荐答案
您可以进行加权随机抽样,而不必担心您的cumsum方法:
You could just do a weighted random sample, without worrying about your cumsum method:
sample(c(1, 2, 3), size = 100, replace = TRUE, prob = c(0.5, 0.1, 0.4))
如果您已经有电话号码,也可以执行以下操作:
If you already have the numbers, you could also do:
x <- runif(10, 0, 1)
as.numeric(cut(x, breaks = c(0, 0.5, 0.6, 1)))
这篇关于以给定的概率生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!