aaaaa
aaaaa

Reputation: 183

Generate random numbers with rbinom but exclude 0s from the range

I need to generate random numbers with rbinom but I need to exclude 0 within the range.

How can I do it?

I would like something similar to:

k <- seq(1, 6, by = 1)

binom_pdf = dbinom(k, 322, 0.1, log = FALSE)

but I need to get all the relative dataset, because if I do the following:

binom_ran = rbinom(100, 322, 0.1)

I get values from 0 to 100.

Is there any way I can get around this?

Thanks

Upvotes: 1

Views: 1134

Answers (2)

John Coleman
John Coleman

Reputation: 52008

In addition to the hit and miss approach, if you want to sample from the conditional distribution of a binomial given that the number of successes is at least one, you can compute the conditional distribution then directly sample from it.

It is easy to work out that if X is binomial with parameters p and n, then

P(X = x | X > 0) = P(X = x)/(1-p)

Hence the following function will work:

rcond.binom <- function(k,n,p){
  probs <- dbinom(1:n,n,p)/(1-p)
  sample(1:n,k,replace = TRUE,prob = probs)
}

If you are going to call the above function numerous times with the same n and p then you can just precompute the vector probs and simply use the last line of the function whenever you need it.

I haven't benchmarked it, but I suspect that the hit-and-miss approach is preferable when k is small, p not too close to 0, and n large, but for larger k larger, p closer to 0, and n smaller then the above might be preferable.

Upvotes: 1

R18
R18

Reputation: 1560

Let`s suppose that we have the fixed parameters:

  • n: number of generated values
  • s: the size of the experiment
  • p: the probability of a success

     # Generate initial values
       U<-rbinom(n,s,p)
       # Number and ubication of zero values
         k<-sum(U==0)
         which.k<-which(U==0)
    
     # While there is still a zero, . . . generate new numbers
       while(k!=0){
         U[which.k]<-rbinom(k,s,p)
           k<-sum(U==0)
           which.k<-which(U==0)
         # Print how many zeroes are still there
           print(k)
     }
    
    # Print U (without zeroes)
      U
    

Upvotes: 3

Related Questions