2
votes

I do not even know if any of my equations are right, but I did this and its saying the objective function in optim evaluates to length 2 not 1. I am trying to estimate lambda and alfa using mle and log likelihood.

set.seed(1001)
q <- 1:5000
mean(q)
sd(q)

ll <- function(lambda = 0.5, alpha = 3.5) {
  n <- 5000
  (-n) * alpha * log(lambda) + 
  n * log(gamma(alpha)) - ((alpha - 1) * sum(log(q))) + 
  lambda * sum(q)
  }


MLE <- optim(c(0.5, 3.5),
  fn = ll,
  method = "L-BFGS-B",
  lower = 0.00001,
  control = list(fnscale = -1),
  hessian = T
)
 
1

1 Answers

1
votes

There are several places to make your optim fly:

  1. you should define your ll as a function of one argument (instead of two arguments, otherwise you will have the error "objective function in optim evaluates to length 2 not 1"), since within optim, your initial value x0 will be pass to objective function fn
ll<-function(x){
  n<-5000
  lambda <- x[1]
  alfa <- x[2]
  (-n)*alfa*log(lambda)+n*log(gamma(alfa))-((alfa-1)*sum(log(q)))+lambda*sum(q)
}
  • In optim, the dimension of lower bound lower should be the same as x0, e.g.,
MLE = optim(c(0.5,3.5), 
            fn = ll, 
            method = "L-BFGS-B", 
            lower = c(1e-5,1e-5), 
            control = list(fnscale = -1), 
            hessian = FALSE
)