user2374133
user2374133

Reputation: 193

How to efficiently calculate binomial probability with list of probabilities? in R

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

Answers (1)

Randy Lai
Randy Lai

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

Related Questions