Search code examples
rprobabilitydistributionprobability-distributionbinomial-cdf

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


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?


Solution

  • 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