Skip to content
Prev 20079 / 63424 Next

change function's formals default values

On Tue, 4 Apr 2006, Andrew Finley wrote:

            
##In R
f<-function(a,b){
   function(x){ a+b*x}
}

f23<-f(a=2,b=3)

dyn.load("cfun.so")
.Call("cfun",fun=f23,rho=environment(f23),x=c(1,2,3,4),newa=1,newb=2)

## in cfun.c

#include "Rinternals.h"

SEXP cfun(SEXP fun, SEXP rho, SEXP x, SEXP newa, SEXP newb){
       SEXP ans, funcall;

       setVar(install("a"), newa, rho);
       setVar(install("b"), newb, rho);

       PROTECT(funcall=lang2(fun,x));
       ans=eval(funcall,rho);

       UNPROTECT(1);
       return ans;

}

##

This isn't necessarily any simpler, but it seems more natural to modify 
variables than default arguments, and also it is probably safer since you 
don't have to worry about the value of NAMED() and whether to copy the 
arguments.

This is based on the more complicated code in cox_Rcallback.c in the 
survival package, for penalized Cox regression
https://svn.r-project.org/R-packages/trunk/survival/src/cox_Rcallback.c

 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle