# [R] Error in optim function.

Berend Hasselman bhh at xs4all.nl
Tue Sep 27 06:53:46 CEST 2011

```jango wrote:
>
> 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
>
>

After defining your binomial.ll function do this

binomial.ll(0.01,y,n)

and you will see that your function is returning a vector of length 6, which
is the length of y.
Your function is returning a vector but should return a scalar.
A likelihood is a scalar so maybe return(sum(output)).

Berend

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

```