Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating expression tree in R

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....

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!

like image 783
tlamadon Avatar asked Dec 22 '11 22:12

tlamadon


People also ask

How do you write an expression in R?

Create an Expression in R Programming – expression() Function. expression() function in R Language is used to create an expression from the values passed as argument. It creates an object of the expression class.

What do you mean by expression tree?

An expression tree is a representation of expressions arranged in a tree-like data structure. In other words, it is a tree with leaves as operands of the expression and nodes contain the operators. Similar to other data structures, data interaction is also possible in an expression tree.

What does the other nodes of an expression tree contains?

What does the other nodes of an expression tree(except leaves) contain? Explanation: The nodes other than leaves always contain only operators. There cannot be any operand in those nodes.


1 Answers

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
}
> 
like image 156
Owen Avatar answered Sep 28 '22 05:09

Owen