Sarah
Sarah

Reputation: 1644

Parameterizations of negative binomial densities (dnbinom) in R

I'm hoping this belongs here rather than a math forum.

I'm trying to calculate in R the density of a negative binomial. My parameters are currently in the form of mu (the mean number of failures expected) and the overdispersion parameter k. Since I'm calling dnbinom in compiled C code, I need to convert these parameters to the default parameterization of dnbinom, which expects the probability of success per trial p and the number of successes n before counting stops. I used the following equations to solve for p and n in terms of mu and k:

n = mu*p/(1-p)
mu + mu^2/k = n(1-p)/p^2

After a bit of algebra, I get

p = k/mu + 1
n = -(mu^2+k*mu)/k

Checking these equations with the different parameterizations of dnbinom in R reveals a problem:

> k = 1.2
> mu = 15
> p = k/mu+1
> n = -(mu*k+mu^2)/k
> dnbinom(10,size=n,prob=p)
[1] NaN
Warning message:
In dnbinom(x, size, prob, log) : NaNs produced
> dnbinom(10,mu=mu,size=k)
[1] 0.03560668

What about R's parameterization am I missing? I'm pretty sure by now that my algebra's correct. Alternatively, is there a way to stick with the original parameterization (in terms of muand k) when calling dnbinom from C?

Upvotes: 3

Views: 2844

Answers (1)

daroczig
daroczig

Reputation: 28642

As ?dnbinom says: size "Must be strictly positive, need not be integer"

In your example

 n = -(mu*k+mu^2)/k
 n
 [1] -202.5

So dnbinom fails.

I think n should be mu*p/(1-p) after calculating p (as you wrote also above), so in this way:

k = 1.2
mu = 15
p = k/(k+mu)
n = mu*p/(1-p)
dnbinom(10,size=n,prob=p)
    [1] 0.03560668
dnbinom(10,mu=mu,size=k)
    [1] 0.03560668

What looks fine.

Upvotes: 6

Related Questions