title: How to fit Negative Binomial on count data in R
body: <p>I want to fit Negative Binomial function on the data of
  pathogen counts(x) which measured in different volumes (v) of 
  water samples. I wrote some codes but they don't work properly. 
  thanks for any helps.</p>
  
  <pre><code>x&lt;-c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
  0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 
  0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
  2L, 2L, 3L, 3L, 3L)
  
  v&lt;-c(48, 51, 52, 54.9, 55, 55, 55, 57, 59, 59, 85.2, 100, 100, 100, 
  100, 100, 100, 100, 100.4, 100.4, 100.6, 100.7, 101.7, 102, 102, 
  102.2, 102.2, 103.3, 185.4, 189.3, 189.3, 190, 191.4, 18.4, 74.1, 
  99.9, 100, 100, 100, 100, 100, 101.1, 101.3, 183.5, 193, 95.8, 
  223.7, 223.7, 227.1, 89.9, 98.4, 100)
  
  #This is Negative binomial function:  
  #PNB(x)= (gamma(x+k)/(gamma(k)*factorial(x)))*
  #        ((mu*V/(k+mu*V))^x)*
  #        ((k+mu*V)/k)^(-k)
  
  #k and mu are the parameters to be optimized.
  
  data&lt;-data.frame(x,v)
  
  NB&lt;-function(par,data){
  A&lt;-gamma(x+par[1])/(gamma(par[1])*factorial(x))
  B&lt;-(par[2]*v/(par[1]+par[2]*v))^par[1]
  C&lt;-((par[1]+par[2]*v)/par[1])^(-par[1])
  return(A*B*C)
  }
  
  best&lt;-optim(par=c(1,1),data=data,NB,gr=NULL,method='BFGS',control=list(trace=12,REPORT=1))
  </code></pre>
  
  <p>it return following error:</p>
  
  <pre><code>Error in optim(par = c(1, 1), data = data, NB, gr = NULL, method = "BFGS",  : 
    objective function in optim evaluates to length 52 not 1
  </code></pre>
  
  <p>I also used <em>fitdistr</em> as follows but it only fits on x without considering the samples volume (v).</p>
  
  <pre><code>&gt; fitdistr (x,"negative binomial")
       size         mu    
    1.3078442   0.5577050 
   (1.1107484) (0.1236888)
  </code></pre>
  
  <p>this mu is independent of v and I think is not correct.</p>