Hadley Wickham
2011-May-04 12:38 UTC
[Rd] Capturing the complete unevaluated expression corresponding to function (body + formals)
Hi all, Is there any way to capture the complete unevaluated expression corresponding to a function? I want the equivalent of x <- quote(function(x) x = 3) But captured after the function is created. Body and formals each captures a part, but is there a built in way to get the whole thing? f <- function(x) x = 3 y <- call("function", formals(f), body(f), attr(f, "source")) identical(x, y) Hadley -- Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/
Duncan Murdoch
2011-May-04 13:07 UTC
[Rd] Capturing the complete unevaluated expression corresponding to function (body + formals)
On 04/05/2011 8:38 AM, Hadley Wickham wrote:> Hi all, > > Is there any way to capture the complete unevaluated expression > corresponding to a function? I want the equivalent of > > x<- quote(function(x) x = 3) > > But captured after the function is created. Body and formals each > captures a part, but is there a built in way to get the whole thing?Internally, "function" is a function that produces a closure object. After you call it and the function is created, the inputs are gone, all you have is the result. But you can reconstruct it as you did below, because "function" basically just glues the parts together (and adds an environment as well). Duncan Murdoch> f<- function(x) x = 3 > y<- call("function", formals(f), body(f), attr(f, "source")) > identical(x, y) > > Hadley >
Hadley Wickham
2011-May-04 13:30 UTC
[Rd] Capturing the complete unevaluated expression corresponding to function (body + formals)
On Wed, May 4, 2011 at 8:07 AM, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:> On 04/05/2011 8:38 AM, Hadley Wickham wrote: >> >> Hi all, >> >> Is there any way to capture the complete unevaluated expression >> corresponding to a function? ?I want the equivalent of >> >> x<- quote(function(x) x = 3) >> >> But captured after the function is created. ?Body and formals each >> captures a part, but is there a built in way to get the whole thing? > > Internally, "function" is a function that produces a closure object. ?After > you call it and the function is created, the inputs are gone, all you have > is the result. ?But you can reconstruct it as you did below, because > "function" basically just glues the parts together (and adds an environment > as well).Ok, I was getting confused because it looks like deparse and print(f, useSource = F) can print the whole thing. But looking at the source, I see that they reconstruct the function from the formals and the body too. Hadley -- Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/