Creating expression tree in R

自作多情 提交于 2019-12-02 20:57:09
> 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

There are a few ways you could construct R expressions programmatically. The most convenient, if it works for your case, is bquote:

> a = 1
> bquote(.(a) + .(a))
1 + 1

where .() is an inverse-quote. This should work for practically anything, but if it does not, there are ways to manually construct the basic building blocks of expressions:

> as.symbol('f')
f
> as.call(list(quote(f), 1, 2))
f(1, 2)
> as.call(list(as.symbol('{'), 1, 2))
{
    1
    2
}
> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!