[R] Optimization of objective function with generic number of arguments (R-Extension with C code)

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Oct 31 12:25:07 CET 2003


I suggest you do this at R level. You can define a function of one arg to
send to your optimizer using lexical scoping to find the rest.  That is
how optim does it:

    fn1 <- function(par) fn(par, ...)

and you just need to write code to figure out which variable you want (it
is not clear to me what your rules are) and do the same.


On Fri, 31 Oct 2003, Paolo Tenconi wrote:

> Hi All! I'm a new subscriber to this mailing list. I'm writing an R 
> extension with C linked code having a minimization function letting me pass 
> it an objective function with a GENERIC number of arguments and letting me 
> to optimize over a specific one among them if there are many.
> 
> 
> #################################################
> ###############  IPOTETICAL MAIN  ###############
> #################################################
> 
> 
> #Objective func with only one parameter
> ObjectiveFunction1<-function(a){
> ...
> }
> 
> #Objective func with two arguments
> ObjectiveFunction2<-function(a,b){
> ...
> }
> 
> 
> #Minimize the first function
> MyOptim(pars,ObjectiveFunction1)
> 
> 
> #Minimize the second function over the first argument
> MyOptim(pars,ObjectiveFunction2,b=xxx)
> 
> 
> #Minimize the second function over the second argument
> MyOptim(pars,ObjectiveFunction2,a=xxx)
> 
> 
> 
> 
> 
> 
> ######################################################
> ##############   EXCERPT OF MY CODE   ################
> ######################################################
> 
> #My R minimization function
> MyOptim <-function(par, fn, ...)
> {
>     ...
>     fn1 <-function(par) fn(par,...)
>     res <-.External(MyOptimC(par, fn1,new.env()))
>     ...
> }
> 
> #My C function
> __declspec (dllexport) SEXP MyOptimC(SEXP args)
> {
>    args = CDR(args); SEXP par = CAR(args);
>     args = CDR(args); SEXP fn = CAR(args);
>     rho  = CDR(args); SEXP rho = CAR(args);
> 
> 
>     SEXP fminfn = lang2(fn, R_NilValue));
>     ...	
> 
> }
> 
> 
> I suceedeed only for objective functions with a specific number of 
> arguments, while for the problem at hand I tried to replicate the code in 
> optim.c and related files but without any result. Is there someone on the 
> list who can me give me some insight, piece of source code or material 
> explaining how to do this?
> 
> Many thanks.
> Paolo
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> 
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list