[R] How to modify the body of a function?

Spencer Graves spencer.graves at structuremonitoring.com
Mon Jul 28 05:27:05 CEST 2014

On 7/27/2014 8:03 PM, super wrote:
> Tks for your opinions, let me describe the background for my question:
> The orignal purpose is to call the function which defined in anothor function, e.g.
> f1<-function(){
> x<-1
> f2<-function(x)
> {x}
> f3<-function(){
> 1+1
> }
> a<-1
> return(x+a)
> }
> The real function  f1  may be very long, And i know there is a function named f3 defined in f1. f3 is useful for me.  For some reason, i can't copy and paste f3's source code manually.
> So, with the solution for modifying the body of a  function, i can do the original task as below:
> oldbody<-body(f1)
> newbody<-bquote({.(redefine);.(oldbody);.(addstuff)},list(redefine=quote(return<-function(x){x}),oldbody=oldbody,addstuff=quote(function(){})))
> body(f1)<-newbody
> closure<-f1()
> ls(environment(closure))
> environment(closure)$f3
> Is there a easy way to do my original task?
> At 2014-07-27 09:41:49, "super" <desolator88 at 163.com> wrote:
>> Suppose that I had a function as below:
>> f<-function() {
>> return(1)
>> }
>> i want to change the body of f  to the form like this:
>> f<-function(){
>> 1
>> function() {}
>> }
>> How can i do the task using body(f) or something else solutions?

       Have you seen Hadley Wickham (2014) Advanced R 
(http://adv-r.had.co.nz)?  It has material that might help you.

       Based partly on this, I wrote Animate1 in Ecfun on R-Forge. This 
includes "bo <- body(fun)".  Then I played around "bo" to find ways of 
working with it.  For example, if fun is a function, then bo[[1]] is 
'{', and length(bo) = the number of "steps" in the function.  A "step" 
in this case could be several lines of code encased in { }.  This may 
not be a very smart way to wrote solid code, but it allowed me to 
produce code that seemed to give me predictable results with all the 
test examples I gave it.

      If anyone has other good references for this, I'm interested.


>> 	[[alternative HTML version deleted]]
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list