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.
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.
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.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With