[R] Error in optim function.

jango terryhughston at gmail.com
Tue Sep 27 04:33:04 CEST 2011


I'm trying to calculate the maximum likelihood estimate for a binomial
distribution.  Here is my code:

y <- c(2, 4, 2, 4, 5, 3)
n <- length(y)
binomial.ll <- function (pi, y, n) {        ## define log-likelihood
  output <- y*log(pi)+(n-y)*(log(1-pi))
  return(output)
}
binomial.mle <- optim(0.01,                     ## starting value
                     binomial.ll,               ## log likelihood
                     method="BFGS",             ## optimization method
                     hessian=TRUE,              ## numerial Hessian
                     control=list(fnscale=-1),  ## max, not min
                     y=y, n=n)
binomial.mle.par <- c(binomial.mle$par, -1/binomial.mle$hessian[1,1])
binomial.mle.par <- as.matrix(binomial.mle.par)
rownames(binomial.mle.par) <- c("lambda", "s.e.")
colnames(binomial.mle.par) <- c("MLE")
print(binomial.mle.par)

When I do this I get the following error message:

Error in optim(0.01, binomial.ll, method = "BFGS", hessian = TRUE, control =
list(fnscale = -1),  : 
  objective function in optim evaluates to length 6 not 1

Any help you can give me would be greatly appreciated.  

--
View this message in context: http://r.789695.n4.nabble.com/Error-in-optim-function-tp3846001p3846001.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list