Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optim function argument missing

Tags:

optimization

r

This is my code. The kum.loglik function returns negative loglikelihood and takes two arguments a and b. I need to find a and b that minimize this function using optim function. (n1,n2,n3 is pre-specified and passed to optim function.

kum.loglik = function(a, b, n1, n2, n3) {
  loglik = n1*log(b*beta(1+2/a,b)) + n2 * log(b*beta(1+2/a,b)-2*b*beta(1+1/a,b)+1) +
    n3 * log(b*beta(1+1/a,b)-b*beta(1+2/a,b))
  return(-loglik)
}
optim(par=c(1,1), kum.loglik, method="L-BFGS-B",
      n1=n1, n2=n2, n3=n3,
      control=list(ndeps=c(5e-4,5e-4)))

This code should work well but it gives error message

Error in b * beta(1 + 2/a, b) : 'b' is missing

What is wrong in this code?

like image 866
user67275 Avatar asked Dec 09 '13 19:12

user67275


2 Answers

The problem is (straight from the optim help):

fn: A function to be minimized (or maximized), with first
argument the vector of parameters over which minimization is
to take place.

Your kum.loglik function needs to take a vector v which you pull the parameters out of, e.g.:

kum.loglik=function(v) { a = v[1]; b = v[2]; ...}

like image 194
jimmyb Avatar answered Sep 22 '22 21:09

jimmyb


I always use the following, it gives you the best results

p0 <- c(a,b) #example vector of starting values
m <- optim(p0, loglik, method="BFGS", control=list(fnscale=-1, trace=10),
hessian=TRUE, x=data.frame)
#for table of results
rbind(m$par, sqrt(diag(solve(-m$hessian))))
like image 21
great_minds_think_alike Avatar answered Sep 23 '22 21:09

great_minds_think_alike