# R program to calculate maximum likelihood (ML) estimates for parameters # k and p in the negative binomial distribution. The distribution is # defined by # gamma(k+x) # P(X=x) = ------------------ (p^k)[(1-p)^x] , for x=0,1,2,3,... # gamma(x+1)gamma(k) # # Here 0 0. pp=exp(-exp(theta[2])) # Constrains 0 < pp < 1. lnnb=lfactorial(kk+xs-1)-lfactorial(xs)-lfactorial(kk-1)+ kk*log(pp)+xs*log(1-pp) ofn=-sum(fs*lnnb) return(ofn) } # The ML estimates. NBML=optim(par=c(log(kk0),log(-log(pp0))), negloglike.ml,NULL,method="Nelder-Mead",fs=ff,xs=xx) results=c(exp(NBML$par[1]),exp(-exp(NBML$par[2])),-NBML$val) k.ml=results[1] # These are the ML estimates. p.ml=results[2] # -- loglike.ml=results[3] expected=nn*exp(lfactorial(k.ml+xx-1)-lfactorial(xx)-lfactorial(k.ml-1)+ k.ml*log(p.ml)+xx*log(1-p.ml)) observed=ff # Print the results. k.ml p.ml loglike.ml cbind(expected,observed)