Skip to content

dynamically creating functions in r

1 message · Carl Witthoft

#
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