Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number with given probability

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.

like image 570
Sophus Bonnen Rossen Avatar asked Oct 08 '15 11:10

Sophus Bonnen Rossen


People also ask

How do you generate random numbers with probability?

Generate random value with probability Select a blank cell which you will place the random value at, type this formula =INDEX(A$2:A$8,COUNTIF(C$2:C$8,"<="&RAND())+1), press Enter key. And press F9 key to refresh the value as you need.

How do you generate a random number from a given distribution in Excel?

To generate a list of random numbers: We can use the RAND function to generate a list of random numbers in Excel. It can be done by filling the first cell with =RAND() and dragging the fill handle till the cell we want, as shown.


Video Answer


1 Answers

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)))
like image 112
jeremycg Avatar answered Sep 22 '22 23:09

jeremycg