Getting the parse tree for a predefined function in R

前端 未结 3 1958
[愿得一人]
[愿得一人] 2021-02-10 05:30

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.

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 06:12

    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()
    
    > 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.

提交回复
热议问题