gpt4 book ai didi

r - 在 R 中创建表达式树

转载 作者:行者123 更新时间:2023-12-04 00:53:12 24 4
gpt4 key购买 nike

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以编程方式对象。理想情况下,我创建了一个复杂列表的对象,其中包含正确的对象,也许我会调用一些 as.languagelist对象。但是,这不起作用。例如:
# 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

感谢您的帮助!

最佳答案

> 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

关于r - 在 R 中创建表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8610303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com