[R] optim

Ken Beath kbeath at efs.mq.edu.au
Wed Jan 3 12:04:15 CET 2007

```The function needs to have a single parameter. Then extract each
parameter.
For example, or see first example in help for optim.
errorFunction <- function(params) {
localShifts <- params[1]
etc

>>> "Gerster  Sarah" <sgerster at student.ethz.ch> 01/03/07 9:22 PM >>>
Hi!

I'm trying to figure out how to use optim... I get some really strange
results, so I guess I got something wrong.

I defined the following function which should be minimized:
errorFunction <-
function(localShifts,globalShift,fileName,experimentalPI,lambda)
{
lambda <- 1/sqrt(147)
# error <- abs(errHuber(localShifts,globalShift,
#
"/home/sarah/Semesterarbeit/Sequences/R/R1593_filtered.data",3.48)) +
#    sum(abs(localShifts))*lambda

error <- sum(abs(localShifts))*lambda
error # return the error to be minimized
}

Then I call optim:
par <- seq(length=9, from=0, by=0)
lambda <- 1/sqrt(147)
globalShift,
"/home/sarah/Semesterarbeit/Sequences/R/R1593_filtered.data",
experimentalPI=3.48, lambda = lambda)

The output is:
\$par
[1]  0.56350964  0.56350964  0.56350964  0.56350964  0.00000000
-0.29515957
[7]  0.00569937  0.32543297  0.18615880

\$value
[1] 0.2529198

\$counts
31       31

\$convergence
[1] 0

\$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"

Warning messages:
1: bounds can only be used with method L-BFGS-B in: optim(par,
errorFunction, gr = NULL, method = "Nelder-Mead",
2: NAs introduced by coercion

If I change my "error-function" to
errorFunction <-
function(localShifts,globalShift,fileName,experimentalPI,lambda)
{
error <- sum(abs(localShifts*lambda))
error # return the error to be minimized
}

or to:
errorFunction <-
function(localShifts,globalShift,fileName,experimentalPI,lambda)
{
error <- sum(abs(localShifts))/sqrt(147)
error # return the error to be minimized
}

The output is:
\$par
[1]  6.018101e-20  6.018101e-20  6.018101e-20  6.018101e-20
0.000000e+00
[6]  5.176245e-21 -4.002183e-21 -8.254019e-20  3.231412e-21

\$value
[1] 2.768593e-20

\$counts
76       76

\$convergence
[1] 0

\$message
[1] "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL"

Warning messages:
1: bounds can only be used with method L-BFGS-B in: optim(par,
errorFunction, gr = NULL, method = "Nelder-Mead",
2: NAs introduced by coercion

- What is wrong with the first version?

Thanks for the help!

Sarah

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help