[R] problem with coding for 'optim' in R
Roger D. Peng
rpeng at stat.ucla.edu
Mon Jul 14 23:26:07 CEST 2003
Heuristically, 'optim' works by changing the imputs to your function 'f'
and tries to find a minimum of the function. But your 'f' function does
not actually reference the imputs that are passed in (i.e. your 'q'
parameter). Therefore, changing the imput values will do nothing and I
would be surprised if 'optim' worked at all. You appear to have another
variable 'q' defined in the global workspace but this is not related to
the 'q' which is passed as an argument to 'f'. 'optim' is modifying the
value of 'q' that is passed to 'f', not the one stored in the global
It seems your interpretation of how 'optim' works is correct, but you
have to rewrite 'f' so that it actually uses the arguments passed to it.
Michael Rennie wrote:
> Hi, Roger,
> At 01:37 PM 7/14/03 -0700, Roger D. Peng wrote:
>> It's important to remember that in R functions return whatever
>> happens to be the last element of the function block, unless there is
>> an explicit 'return' statement. Your function 'f' in the second
>> example is written incorrectly and will not work in 'optim'. The
>> last element in the function block is:
>> write.table (bioday, file = "perch.csv", append = FALSE, sep=",", na
>> = NA, col.names = TRUE)
>>> which I assume is *not* the value you want the function return.
>>> Your function 'f' is returning whatever 'write.table' returns, which
>>> is nothing useful. My guess is that you want your function 'f' to
>>> return the value 'f' defined in the function as
>>> f <- (((Wt-Wtmod)^2 + (Hgt-Hgtmod)^2)/2)^2
>>> So this statement should be the last line of your function.
> This is valuable information. Thanks very much. I'll move things
> about and see what happens.
>>> Also, your function 'f' (still from the second output) doesn't use
>>> the value 'q' at all, so I can't see how the optimizer can optimize
>>> a function that ignores its parameters.
> From what I've read and the examples I've encountered, the 'optim'
> function expects the first entry in
> optim(x, f, etc....)
> To be the starting point for your variable that you specify earlier in
> the loop under
> f<- function (x)
> If I am wrong on this, then this could be giving me problems as well.
> Michael Rennie
> M.Sc. Candidate
> University of Toronto at Mississauga
> 3359 Mississauga Rd. N.
> Mississauga, ON L5L 1C6
> Ph: 905-828-5452 Fax: 905-828-3792
More information about the R-help