Skip to content
Prev 40037 / 63424 Next

Capturing the expression representing the body of a function

On 02/05/2011 3:21 PM, Hadley Wickham wrote:
The body of a function isn't an expression, it's a language object.  A 
language object is represented internally as a pairlist, while an 
expression is represented as a generic vector, i.e. the thing that 
list() gives.

Your 1st try gives you the language object.

The other ones only work when the body consists of a call to `{`, as the 
body of most complex functions does, but not for simple ones like

f <- function(x) 2*x

So I would say your question should be:  "What's the best way to 
construct an expression vector s.t. evaluating its elements in order is 
like evaluating the body of a function?"

And the answer to that is something like

body2expr <- function(f) {
   body <- body(f)
   if (typeof(body) == "language" && identical(body[[1]], quote(`{`))) 
as.expression(as.list(body[-1]))
   else as.expression(body)
}

Duncan Murdoch