[R] computing on expressions

Duncan Murdoch murdoch at stats.uwo.ca
Fri Oct 3 18:41:22 CEST 2008


On 10/3/2008 11:48 AM, Vadim Organovich wrote:
> Dear R-users,
> 
> Suppose I have an expression:
> 
> expr = expression(a>0)
> 
> and now I want to modify it to expression(a>0 & b>0). The following doesn't work:
> 
> expr = expression(expr & b>0)
> 
> What would be a good way of doing this?

I'd avoid using parse because it doesn't generalize well.  Here's a way 
to do it without that.  But first, some background:

expression() returns a special kind of list that contains language 
objects.  So expr[[1]] is initially  a>0, and you want to change it to 
a>0 & b>0.  I think you don't really want expr & b>0, because that would 
be    expression(a>0) & b>0  which is nonsense.

The bquote() function is probably the easiest way to make substitutions. 
  The idea is that you write out the answer you want within bquote(), 
using .() around things you want substituted.  (You can also use the 
substitute() function, but it's a little trickier.)

Putting these together, this gives you the final result you want:

expr <- expression(a>0)
expr[[1]] <- bquote( .(expr[[1]]) & b>0 )

The following lines almost give you what you want:

expr2 <- expression(a>0)
expr2 <- bquote( expression( .(expr2[[1]]) & b>0 ) )

but not quite:  expr2 becomes an unevaluated call to the expression() 
function, not an actual expression (though they print the same).  You 
need this for the equivalent to the first version:

expr2 <- expression(a>0)
expr2 <- eval( bquote( expression( .(expr2[[1]]) & b>0 ) ) )

Duncan Murdoch



More information about the R-help mailing list