title: Parameterizations of negative binomial densities (dnbinom) in R
body: <p>I'm hoping this belongs here rather than a math forum.</p>
  
  <p>I'm trying to calculate in R the density of a negative binomial. My parameters are currently in the form of <code>mu</code> (the mean number of failures expected) and the overdispersion parameter <code>k</code>. Since I'm calling <code>dnbinom</code> in compiled C code, I need to convert these parameters to the default parameterization of <code>dnbinom</code>, which expects the probability of success per trial <code>p</code> and the number of successes <code>n</code> before counting stops. I used the following equations to solve for <code>p</code> and <code>n</code> in terms of <code>mu</code> and <code>k</code>:</p>
  
  <pre><code>n = mu*p/(1-p)
  mu + mu^2/k = n(1-p)/p^2
  </code></pre>
  
  <p>After a bit of algebra, I get</p>
  
  <pre><code>p = k/mu + 1
  n = -(mu^2+k*mu)/k
  </code></pre>
  
  <p>Checking these equations with the different parameterizations of <code>dnbinom</code> in R reveals a problem:</p>
  
  <p><pre><code>> 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
  </pre></code></p>
  
  <p>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 <code>mu</code>and <code>k</code>) when calling <code>dnbinom</code> from C?</p>