在R中创建表达式树 [英] Creating expression tree in R

查看:82
本文介绍了在R中创建表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R中的替代函数以树的形式创建了一个可以解析的语言对象.如何使用list从头开始创建树,否则将其交给eval?

The substitute function in R creates a language object in the form of a tree that one can parse. How can I create the tree from scratch using list or else to then give it to 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.但是,这不起作用.例如:

I would like to know how I can reconstruct the e1 object programmatically. Ideally I create an object of intricated lists with the correct object in them and maybe I call some as.language on the list object. However that does not work. For instance:

# 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",然后对其进行解析,但是当您首先将树放在首位时,生成字符串以再次对其进行解析似乎并不优雅!

One way is to just generate the string '1+1' and then parse it, but it does not seem elegant to generate strings to parse them again when you have the tree in the first place!

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中创建表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆