[R] Passing parameters to 'optim' fn function

Duncan Murdoch murdoch at stats.uwo.ca
Wed Sep 12 12:36:14 CEST 2007


José Luis Aznarte M. wrote:
>     Hi again! I'm using the 'optim' method to fix the parameters of a 
> model. I have written the function to be minimised and another function 
> which returns the gradient of the error. Now my problem is that, in 
> order to compute that gradient, it would be extremely convenient to be 
> able to pass some parameters to the gradient function. I don't see how 
> to do it given the fixed syntax of 'optim', which does not allow for 
> parameters being passed to fn and gr:
>
>  > optim(par, fn, gr = NULL, ...)
>
>     Of course the first idea would be to "pack" the extra parameters in 
> the vector 'par', but in that case the extra parameters would be 
> optimized too.
>     Does anyone have an idea on how to pass parameters to gr in optim? 
> Thanks for your time!
>   

You can put the parameters in the ... argument (watch out for matches to 
earlier optim args!), or into the environments of fn and gr.  For example,

makefn <- function(x) {
  fn <- function(mu) sum((x-mu)^2)
  gr <- function(mu) sum(2*(mu-x))
  list(fn = fn, gr = gr)
}
x <- rnorm(10)
fg <- makefn(x)
optim(1, fg$fn, fg$gr)

Duncan Murdoch



More information about the R-help mailing list