# How to draw random samples from a negative binomial distribution in R?

Let $X$ have the Negative Binomial distribution with parameters $r$ and $p$. The Negative Binomial distribution is a mixture distribution or compound distribution. That is $X$ is $\text{Poisson}(\lambda)$ where $\lambda$ is randomly chosen from a $\text{Gamma}(r, p/(1-p))$. Use this relation to write an R function for randomly drawing $n$ Negative Binomial random samples. Hint: Use the R functions rpois and rgamma.

-
If this is homework, please tag it accordingly. Someone will probably help you provided you indicate where you get in trouble. –  chl Nov 28 '11 at 2:21
If it's indeed a homework Q, you certainly get more fun questions than I do. :) –  Roman Luštrik Nov 28 '11 at 9:13
As indicated in the OP's the comment to Xi'an's post, I have added the homework tag to this question. –  cardinal Nov 28 '11 at 13:56

The answer is contained in the description of the mixture decomposition of the negative binomial distribution as a Poisson distribution where the parameter is itself random with a Gamma distribution. How much more of a hint do you need?

-
yes this is hoemwork. I used rgamma to initially generate a random variable. that random variable i allotted to the value of lamdba and used that for the lambda in rpois. But it doesnt work. Pls tell me where im wrong. –  probabilityman Nov 28 '11 at 13:53
x <- rgamma(1, shape=2, rate=0.1) x lambda <- x ylim <- c(0:1) y1 <- rpois(n, lambda) plot (y1, ylab="probability" ,ylim= ylim, type= 'hist'' ) –  probabilityman Nov 28 '11 at 13:53
@cardinal: to me it should be an answer, namely that it is not the purpose of the forum to do someone's homework. Comments are prone to be overlooked. –  Xi'an Nov 28 '11 at 14:11
@probabilityman: your R code simulates one single $\lambda$ and reuses it in $n$ Poisson $\mathcal{P}(\lambda)$ simulations. This is not what is indicated by the compound representation of the negative binomial random variable, compound of one Poisson variable and of one Gamma variable. –  Xi'an Nov 28 '11 at 14:13
I agree we should not be doing other people's homework for them. That was not the intent of my comment. :) I think @whuber's edit clarifies the post a bit. Cheers. –  cardinal Nov 28 '11 at 18:32
If this is not a homework question, you're probably better off with the rnbinom function from stats. If you're lucky (I haven't checked) you can check it's source to see how the implementers did it.