Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a function with parameters in optim in R

Tags:

People also ask

How does the Optim function work in R?

optim can be used recursively, and for a single parameter as well as many. It also accepts a zero-length par , and just evaluates the function with that argument. Non-negative integer. If positive, tracing information on the progress of the optimization is produced.

What is Nlminb?

nlminb() takes a function, objective, and finds values for the parameters of this function at which the objective function acheives its minimum value. Unlike optimize(), nlminb() can be used to optimize functions with mutiple arguments.

How do I speed up my Optim in R?

optim uses a slow algorithm as the default. You can gain a > 5-fold speedup by using the Quasi-Newton algorithm (method="BFGS") instead of the default. If you're not concerned too much about the last digits, you can also set the tolerance levels higher of nlm() to gain extra speed.


I am trying to use the optim function in R - I have no problems with this:

funk=function(param){
  x=c(1,2,3,4,5)
  z=c(3,4,2,2,1)
  y=c(30,40,22,33,40)
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1),fn=funk)
#

But as soon as I don't want to hard-code my data (x,y,z) into the function I have problems. How do I optimize a function in optim when the function input is more than just the parameters to be optimized? Ideally I would pass on value of xx, zz, yy then optimize, then move to differnt values of xx, zz, yy and optimize that case next.

xx=c(1,2,3,4,5)
zz=c(3,4,2,2,1)
yy=c(30,40,22,33,40)

funk=function(param,x,y,z){
  a=rep(param[1],5)
  b=param[2]
  d=param[3]
  fit=sum((y-(a+b*x+z*d))^2)
  return(fit)
}

optim(par=c(1,1,1),fn=funk(param=c(0,0,0),x=xx,y=yy,z=zz))

Error in (function (par) : could not find function "fn"