Reputation: 193
I have a list of probabilities of success for independent events:
probs <- c(.2,.3,.4)
I want to write a function that answers the question: what is probability of getting at least X successes from these independent events?
My current approach is to run the following code thousands of times using a for loop. Is there a more efficient way?
sim_results <- probs - runif(length(probs), 0, 1)
length(sim_results[sim_results > 0])
Upvotes: 0
Views: 276
Reputation: 3174
Try to generate all random numbers in one shot and avoid for loops.
# number of random probabilities
p = 100
# number of simulations
N = 1000
# random probabilities
probs = runif(p)
M = matrix(runif(p*N), N, p)
# outcome
y = apply(M,1,function(x) sum(probs>x))
hist(y)
Upvotes: 1