[R] dynamically creating functions in r

Carl Witthoft carl at witthoft.com
Thu Oct 6 00:03:34 CEST 2011


Another way to build functions "from scratch" :

 > func<-'x^2+5'

 > funcderiv<- D(parse(text=func), 'x') )

 > newtparam <- function(zvar) {}

 > body(newtparam)[2]  <- parse(text=paste('newz  <- 
(',func,')/eval(funcderiv)',collapse=''))


 > body(newtparam)[3] <- parse(text=paste('return(invisible(newz))'))

 > newtparam

function (zvar)
{
     newz <- (x^2 + 5)/eval(funcderiv)
     return(invisible(newz))
}


The important thing to know if you go with this method is that 
body(your_function)[1]  is always "{}"

Carl

-- 
-----
Sent from my Cray XK6



More information about the R-help mailing list