[R] Computing on the language redux

Bert Gunter gunter.berton at gene.com
Mon Oct 6 19:22:19 CEST 2008


Warning: This is only for those interested in R language minutiae

A recent post on this list asked if there was a simple way to change the R
language object:

ex1 <- expression(x < a) ## just the part to the right of the <- assignment

to the object

expression( x < a & y < b)   ## or something like this

Phil Spector showed how to do this by essentially deparsing and reparsing
the string:

parse(text =paste(ex1, "& y < b"))

Howwever, Duncan Murdoch commented in a subsequent post that this approach
might fail under certain circumstances and that a better approach would be
to compute on the language object directly using the bquote() function:

ex1[[1]] <- bquote( .(ex1[[1]]) & y < b)

The important idea that Duncan highlighted was that expressions are just
special kinds of lists (parse trees, actually) and that this allows the list
assignment shown. He also mentioned that bquote() was a convenience function
based on the fundamental language object function, substitute(), and that
substitute() could be used directly, but it was somewhat tricky. For
completeness, I just wanted to show the substitute construction, which
actually doesn't seem all that tricky to me. Here is the complete code
sequence to check:

ex1 <- expression(x < a)   ## original
ex2 <- bquote( .(ex1[[1]]) & y < b) ## Using bquote
ex3 <- substitute( z & y < b,list(z = ex1[[1]])) ## using substitute
directly
identical(ex2,ex3) ##  TRUE


Cheers to all,

Bert Gunter
Genentech Nonclinical Statistics



More information about the R-help mailing list