在R中创建表达式树

在R中创建表达式树,r,tree,eval,substitution,R,Tree,Eval,Substitution,R中的替代函数以树的形式创建一个可以解析的语言对象。如何使用list或else从头开始创建树,然后将其交给eval # substitute gives a tree representation of the expression a=1; b=2; e1 = substitute(a+2*b) eval(e1) #gives 5 as expected e1 # is type language e1[[1]] # this is `+` e1[[

R
中的替代函数以树的形式创建一个可以解析的语言对象。如何使用list或else从头开始创建树,然后将其交给eval

# substitute gives a tree representation of the expression
a=1; b=2;
e1 = substitute(a+2*b)
eval(e1)      #gives 5 as expected
e1            # is type language
e1[[1]]       # this is `+`
e1[[2]]       # this is 'a' type symbol
e1[[3]]       # this is type language
e1[[3]][[1]]  # this is `*`  etc....
我想知道如何以编程方式重构
e1
对象。理想情况下,我会创建一个包含复杂列表的对象,其中包含正确的对象,也许我会在
列表
对象上调用一些
作为.language
。然而,这是行不通的。例如:

# how to construct the tree?
eval(list(as.symbol('+'),1,1))                # does not return 2
eval(as.expression(list(as.symbol('+'),1,1))) # does not return 2
一种方法是只生成字符串“1+1”,然后对其进行解析,但当您首先有了树时,再生成字符串对其进行解析似乎并不优雅

eval(parse(text='1+1')) # does return 1, but not elegant if tree is 
                        # large and already in memory 

谢谢你的帮助

有几种方法可以通过编程方式构造R表达式。如果对您的案例有效,最方便的方法是
bquote

> a = 1
> bquote(.(a) + .(a))
1 + 1
其中,
()
是反引号。这实际上适用于任何情况,但如果不适用,则有多种方法可以手动构造表达式的基本构建块:

> as.symbol('f')
f
> as.call(list(quote(f), 1, 2))
f(1, 2)
> as.call(list(as.symbol('{'), 1, 2))
{
    1
    2
}
> 
>plus
函数(e1,e2)。原语(“+”)
>时间=.Primitive(“*”)
>评估(呼叫(“加”,b,呼叫(“次数”,2,b)))
[1] 6
>评估(呼叫(“加”,a,呼叫(“次数”,2,b)))
[1] 5

太好了,
as.call
实际上就是我要找的。从2个表达式如何将它们组合成第三个表达式和
as.call(list(as.symbol(+')、e1、e2))
works@tlamadon注意,这应该相当于
bquote((e1)+(e2))
甚至更好,所以我可以通过
调用('+',e1,e2)
将2个表达式与一个加号完美地结合起来!
> plus <- .Primitive("+")
> plus
function (e1, e2)  .Primitive("+")
> times=.Primitive("*")
> eval(call("plus", b, call("times",2, b)))
[1] 6
> eval(call("plus", a, call("times",2, b)))
[1] 5