Theodor
Theodor

Reputation: 1026

Use optimize() for a function which returns several values

Easier to ask by example. If I have a function

fn <- function(x) {
...
return(c(a,b,c))
}

and I wish to maximize (or minimize) with respect to a, but also get the values of b and c at the optimal value.

Of course I can use fn2 <- function(x) fn(x)[1] to determine the optimal value, then call the function again, but I wonder if there is a smarter way of doing this.

Upvotes: 1

Views: 127

Answers (1)

Dason
Dason

Reputation: 61983

optim needs the return value to be a scalar. The documentation says so

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

You could write the values of interest to a global variable inside your function though. This isn't necessarily best practice but it could work.

f <- function(x){
  .vals <<- c(x, x+1)
  x^2
}
optim(1, f)

then after we can look at what is stored in .vals

> .vals
[1] 9.765625e-05 1.000098e+00

Upvotes: 1

Related Questions