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
e1 = substitute(a+2*b)
eval(e1) #gives 5 as expected
e1 # is type language
e1[] # this is `+`
e1[] # this is 'a' type symbol
e1[] # this is type language
e1[][] # this is `*` etc....
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
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
Thanks for your help!
以上就是Creating expression tree in R的详细内容，更多请关注web前端其它相关文章！