7

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.

Community
  • 1
  • 1
  • if you did want to do this without `sample()` you could probably use `findInterval()` ... – Ben Bolker Oct 08 '15 at 12:31
  • Does this answer your question? [Draw random numbers from pre-specified probability mass function in Matlab](https://stackoverflow.com/questions/58607156/draw-random-numbers-from-pre-specified-probability-mass-function-in-matlab) – SecretAgentMan Oct 29 '19 at 16:11

1 Answers1

13

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)))
jeremycg
  • 24,657
  • 5
  • 63
  • 74
  • 1
    @SophusBonnenRossen If Jeremycg's answer helped you please mark it as correct answer! – Bas Oct 08 '15 at 12:12