[R] 'optim' and extra argument to the objective function

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Oct 20 21:01:16 CEST 2003


On Mon, 20 Oct 2003, Laurent Gautier wrote:

> I'd like to use optim, and give extra arguments to the objective
> function. The man page says that the '...' should let one do it,
> but I have a hard time to understand how.

Try reading up on argument matching, then.  E.g. in `S Programming'
(see the R FAQ).

> Example:
> 
> x <- 1:10
> y <- rnorm(10)
> cost.f <- function(par, x, y) {
>  A <- par[1]
>  cost <- sum( (log(A*x) - log(y))^2)
>  return(cost)
> }
> 
> optim(3, cost.f, x, y)
> ## returns:
> Error in pmatch(x, table, duplicates.ok) : 
> 	argument is not of mode character
> ## uh, uh... may the problem is with the argument matching ?
> optim(3, cost.f, method="BFGS", x, y)
> ## returns:
> Error in log(A * x) : Argument "x" is missing, with no default
> In addition: Warning message: 
> bounds can only be used with method L-BFGS-B in: optim(3, cost.f, method = "BFGS", x, y) 
> 
> Any suggestion ?

optim(3, cost.f, method="BFGS", x=x, y=y)

except that some component of y is negative with high probability ....

You do have to *name* arguments in ... -- that's standard S/R syntax.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list