Søren Højsgaard
2006-Feb-14 15:43 UTC
[R] Using optim() with a function which returns more than a scalar - alternatives?
I want to numerically maximize a function with optim (maximization over several arguments). optim() needs a function which returns a scalar only. However, it could be nice to be able to "take other things out" from the function as well. I'tried to create an attribute to the scalar with what I want to take out, but that attribute disappears in optim(). I looked into the code to see if it could (easily) be modified such that it could work on a function which returns e.g. a list or a vector (and then it should be maximized over the first element). But I gave up... Any suggestion will be appreciated... Best regards S??ren
Barry Rowlingson
2006-Feb-14 16:06 UTC
[R] Using optim() with a function which returns more than a scalar - alternatives?
S??ren H??jsgaard wrote:> I want to numerically maximize a function with optim (maximization > over several arguments). optim() needs a function which returns a > scalar only. However, it could be nice to be able to "take other > things out" from the function as well. I'tried to create an attribute > to the scalar with what I want to take out, but that attribute > disappears in optim(). I looked into the code to see if it could > (easily) be modified such that it could work on a function which > returns e.g. a list or a vector (and then it should be maximized over > the first element). But I gave up... Any suggestion will be > appreciated...Have your function return a scalar value and any additional data in an attribute, and then optimise. Then call your function one more time using the resulting parameters found by optim(), and you'll get the attributes. Pro: No need to mess with the code of optim() Con: One more function call required. Probably not a problem since optim() will have called it a few times anyway. BArry
Seemingly Similar Threads
- Saving data in an R package - how to maintain that t avariable is a 'factor' when it is coded as 1, 2, 3...
- Contrasts in lm
- Calling substitute(expr, list(a=1)) when expr <- expression(a+b+c)
- Evaluating f(x(2,3)) on a function f<- function(a,b){a+b}
- 'invalid HOMEDRIVE'