From dutangc at gmail.com  Thu Oct  8 19:58:20 2015
From: dutangc at gmail.com (Christophe Dutang)
Date: Thu, 8 Oct 2015 19:58:20 +0200
Subject: [Rd] names treatment in optim()
In-Reply-To: <5BD131B0-C1B7-43FE-A309-3082EBE80807@gmail.com>
References: <5BD131B0-C1B7-43FE-A309-3082EBE80807@gmail.com>
Message-ID: <C216D74B-6503-45B8-8F43-32FFE52DE488@gmail.com>

Dear list,

A possible patch to correct the treatment of names consists in adding the following lines

    if(!is.null(names(par))) names(res$par) <- names(par)  
    if(!is.null(names(fn1(par)))) names(res$value) <- names(fn1(par)) 

 just before returning the variable res in optim. That is 

optim <-
    function(par, fn, gr = NULL, ...,
             method = c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"),
             lower = -Inf, upper = Inf,
             control = list(), hessian = FALSE)
{
?

    if (hessian)
        res$hessian <- .External2(C_optimhess, res$par, fn1, gr1, con)
    if(!is.null(names(par))) names(res$par) <- names(par)  
    if(!is.null(names(fn1(par)))) names(res$value) <- names(fn1(par)) 
    res
}

Regards, Christophe

---------------------------------------
Christophe Dutang
LMM, UdM, Le Mans, France
web: http://dutangc.free.fr

> Le 17 sept. 2015 ? 13:04, Christophe Dutang <dutangc at gmail.com> a ?crit :
> 
> Dear both,
> 
> I have found that names are not treated in the same way in optim() depending on the optimization method (argument method). 
> 
> The example below shows the difference between the Brent method and the L-BFGS-B method.
> 
> f <- function(x){ y <- x^2;names(y) <-"f(x)";y}
> optim(10, f, method="Brent", lower=-1, upper=10)$value
> optim(10, f, method="L-BFGS-B", lower=-1, upper=10)$value
> 
> z <- 10
> names(z) <- "x"
> z
> optim(z, f, method="Brent", lower=-1, upper=10)$par
> optim(z, f, method="L-BFGS-B", lower=-1, upper=10)$par
> 
> 
> Do you obtain the same behavior? would you consider interesting to have the names passed to the components value and par?
> 
> I?m using R version 3.2.2 (2015-08-14)
> Platform: x86_64-apple-darwin13.4.0 (64-bit)
> Running under: OS X 10.10.5 (Yosemite)
> 
> locale:
> [1] fr_FR.UTF-8/fr_FR.UTF-8/fr_FR.UTF-8/C/fr_FR.UTF-8/fr_FR.UTF-8
> 
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base   
> 
> 
> 
> Kind regards, Christophe
> 
> ---------------------------------------
> Christophe Dutang
> LMM, UdM, Le Mans, France
> web: http://dutangc.free.fr
> 



[Rd] names treatment in optim()
Christophe Dutang