Getting a parse tree for a predefined function in R

It seems to me that this is a fairly simple question, but I can not understand it.

If I define a function in R, as I later use the function name to get its parsing tree. I cannot just use substitute , as this will simply return a parsing tree for its argument, in this case just the name of the function.

For instance,

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

How can I access the function syntax tree using its name? For example, how to get the value substitute(function(x){ x^2 }) without explicitly writing the entire function?

+4
source share
3 answers

I'm not quite sure which of them fit 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 view may not display the full functions of the return values.

  class(substitute(function(x){ x^2 }) ) #[1] "call" class( eval(f) ) #[1] "function" 
+4
source

The substitute function can be substituted into environment-bound values. It is strange that its argument env does not have a default value, but by default it belongs to the evaluation environment. It seems that this behavior does not work when the evaluation environment is a global environment, but otherwise works fine.

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 shown, when using the global environment as the second argument, the function does not work.

Another demonstration that it works correctly using a , but not a global environment:

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

Pretty strange.

+2
source

Apparently this is really some kind of weird substitute quirk and is mentioned here :

/ * do_substitute has two arguments, an expression and an environment (optional). The characters found in the expression are replaced by their values ​​found in the environment. There is no inheritance, so only the supplied environment is searched. If there is no environment, indicate the environment in which. If the specified environment is R_GlobalEnv, it is converted to R_NilValue for historical reasons. In substitute (), R_NilValue signals that no replacement should be performed, only the extraction of promising expressions. The arguments for do_substitute should not be evaluated. * /

And you have already found a way around it:

 e = new.env() e$fn = f substitute(fn, e) 
+2
source

Source: https://habr.com/ru/post/1485701/


All Articles