Generate random number with given probability

主宰稳场 提交于 2020-01-31 10:51:30

问题


I have a question which is basically the vectorized R solution to the following matlab problem:

Generate random number with given probability matlab

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.

So basically I'm looking for the R solution to Oleg's vectorized solution in matlab (from the comments to the matlab solution):

"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.


回答1:


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)))


来源:https://stackoverflow.com/questions/33015000/generate-random-number-with-given-probability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!