rbinom; How to ensure at least one "success" is returned?

146 Views Asked by At

Is there a way to ensure rbinom() returns at least one success?

I am running rbinom() with a really low probability:

rbinom(5015, size=2, prob= 1/5000))

Since it is a probability distribution, there is a chance all 0s are returned. Is there a way to ensure that at there is at least one success returned?

3

There are 3 best solutions below

3
jpsmith On BEST ANSWER

A simple while loop can be written to keep iterating until there is at least one success in the vector (here, defined as x):

x <- 0
while(sum(x) == 0) {
  x <- rbinom(5015, size=2, prob= 1/5000)
}

# check

table(x)
#x
#   0    1 
#5013    2 # here there were two
0
Lil' Pete On

The short answer is no, but (depending on your application) you could continue to generate binomial outcomes until you have a success.

out = rbinom(5015, size=2, prob= 1/5000)
resp = any(out>0)
count = 1
while (!resp) {
    count = count + 1
    out = c(out, rbinom(5015, size = 2, prob = 1/5000))
    resp = any(out>0)
}
cat("\nNumber of iterations =",count)
7
Ben Bolker On

An alternative to the while loop suggestion: if the values are all zero, pick one at random and set it to 1 instead.

n <- 5015
r <- rbinom(n, size=2, prob= 1/5000))
if (all(r == 0)) {
   r[sample(n, size = 1)] <- 1
}

This is sort of hacky, but potentially more efficient than repeated simulation (e.g., if you used the while suggestion with n = 1000 and prob = 1e-10 you could be waiting a long time ...). Since it's hard to think of a principled way to modify the statistical distribution to enforce this (since it effectively requires defining a multivariate distribution), this approach might be as good as anything else.