中的替代函数R
以可以解析的树的形式创建一个语言对象。如何使用 list 从头开始创建树,然后将其交给 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.language
on the list
目的。但这不起作用。例如:
# 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
where .()
是一个反引号。这几乎适用于任何东西,但如果不行,有一些方法可以手动构造表达式的基本构建块:
> as.symbol('f')
f
> as.call(list(quote(f), 1, 2))
f(1, 2)
> as.call(list(as.symbol('{'), 1, 2))
{
1
2
}
>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)