【发布时间】:2011-12-22 22:12:30
【问题描述】:
R 中的替代函数以可以解析的树的形式创建语言对象。如何使用列表从头开始创建树,然后将其提供给 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 对象。理想情况下,我创建一个包含正确对象的复杂列表对象,也许我在list 对象上调用了一些as.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 tree eval substitution