[R] substitute question

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Mar 20 11:23:20 CET 2004


Tony Plate <tplate at blackmesacapital.com> writes:

> Earlier in this discussion, Peter Dalgard stated "you can only do
> substitutions on language objects" and then used the function
> is.language() in an example, which I took at that time to imply that
> substitute() would go inside objects for which is.language() returned
> true.  However, from experimenting, it seems that is.call() rather
> than is.language() is the appropriate test.

Right. That surprised me too, although perhaps it shouldn't have. Of
course we might just have looked at the source, where we see that
PROMSXP, SYMSXP, and LANGSXP are handled, and everything else,
including EXPRSXPs are returned as is. I think this is deliberate and
that expression objects are occasionally used as a quoting mechanism
to prevent substitutions from taking place, but my recollection is a
bit hazy on this point. So at the R level it is is.name() or is.call()
or promises evaluating to either of the two.

Notice, BTW, that expression() is "weird" in the same way as
the function(...)... constructs that tripped Gabor:

> substitute(expression(a+b),list(b=2))
expression(a + 2)
> eval(substitute(substitute(e,list(b=2)), list(e=expression(a+b))))
expression(a + b)
> eval(substitute(substitute(e,list(b=2)), list(e=quote(expression(a+b)))))
expression(a + 2)

and the root cause of this is that  

> expression(a+b)
expression(a + b)
> quote(expression(a+b))
expression(a + b)

There's a group of cases where deparse and parse are not exact
inverses, because some objects are not directly representable in the
language, so you get instead a function call that *evaluates* to a
similar object; the simplest case is vectors of length > 1:

> dput(rnorm(1))
-0.214713202300464
> dput(rnorm(2))
c(0.92727004398074, 0.437854016853309)


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list