Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the parse tree for a predefined function in R

I feel as if this is a fairly basic question, but I can't figure it out.

If I define a function in R, how do I later use the name of the function to get its parse tree. I can't just use substitute as that will just return the parse tree of its argument, in this case just the function name.

For example,

> f <- function(x){ x^2 }
> substitute(f)
f

How should I access the parse tree of the function using its name? For example, how would I get the value of substitute(function(x){ x^2 }) without explicitly writing out the whole function?

like image 346
Jon Claus Avatar asked Jun 11 '13 21:06

Jon Claus


2 Answers

I'm not exactly sure which of these meets your desires:

 eval(f)
#function(x){ x^2 }

 identical(eval(f), get("f"))
#[1] TRUE
 identical(eval(f), substitute( function(x){ x^2 })  )
#[1] FALSE

 deparse(f)
#[1] "function (x) " "{"             "    x^2"       "}"            

 body(f)
#------
{
    x^2
}
#---------

eval(parse(text=deparse(f)))
#---------
function (x) 
{
    x^2
}
#-----------

 parse(text=deparse(f))
#--------
expression(function (x) 
{
    x^2
})
#--------

 get("f")
# function(x){ x^2 }

The print representation may not display the full features of the values returned.

 class(substitute(function(x){ x^2 }) )
#[1] "call"
 class( eval(f) ) 
#[1] "function"
like image 145
IRTFM Avatar answered Sep 28 '22 06:09

IRTFM


The function substitute can substitute in values bound to an environment. The odd thing is that its env argument does not possess a default value, but it defaults to the evaluation environment. This behavior seems to make it fail when the evaluation environment is the global environment, but works fine otherwise.

Here is an example:

> a = new.env()
> a$f = function(x){x^2}
> substitute(f, a)
function(x){x^2}
> f = function(x){x^2}
> environment()
<environment: R_GlobalEnv>
> substitute(f, environment())
f
> substitute(f, globalenv())
f

As demonstrated, when using the global environment as the second argument the functionality fails.

A further demosntration that it works correctly using a but not the global environment:

> evalq(substitute(f), a)
function(x){x^2}
> evalq(substitute(f), environment())
f

Quite puzzling.

like image 39
Jon Claus Avatar answered Sep 28 '22 06:09

Jon Claus