[Rd] An exercise in the use of 'substitute'

Gabor Grothendieck ggrothendieck at gmail.com
Sat Apr 2 03:21:48 CEST 2005


On Apr 1, 2005 7:12 PM, Douglas Bates <bates at stat.wisc.edu> wrote:
> I would like to create a method for the generic function "with" applied
> to a class of fitted models.  The method should do two things:
> 
> 1. Substitute the name of the first argument for '.' throughout the
> expression
> 
> 2. Evaluate the modified expression using the data argument to the
> fitted model as the first element of the search list.
> 
> The second part is relatively easy.  The default method for "with" has body
>   eval(substitute(expr), data, enclos = parent.frame())
> and you just change this to
>   eval(substitute(expr), eval(data$call$data), enclos = parent.frame())
> 
> So, for example
> 
> > fm <- lm(optden ~ carb, Formaldehyde)
> > with.lm <- function(data, expr, ...) eval(substitute(expr),
> eval(data$call$data), enclos = parent.frame())
> > with(fm, carb)
> [1] 0.1 0.3 0.5 0.6 0.7 0.9
> 
> However, I haven't been able to work out a clever way of using
> substitute to get the first part.  I would like to be able to call, e.g.
> 
> with(fm, xyplot(resid(.) ~ carb))
> 
> and get a plot of resid(fm) ~ Formaldehyde$carb
> 
> It is possible to do the first part by deparsing, substituting, and
> parsing but that's inelegant.  Can anyone suggest a more elegant method?
> 
> BTW, the example of an lm model is just for illustration.  The actual
> use I have in mind is for lme (now lmer) models.  The plot method for
> the lme class in the nlme package does something very similar to this.

This seems to work, at least on your examples:

> with.lm <- function(data, expr, ...) eval(substitute(expr), 
+      append(model.frame(data), list(. = data)), parent.frame())
> 
> library(lattice)
> data(Formaldehyde)
> fm <- lm(optden ~ carb, Formaldehyde)
> with(fm, carb)
[1] 0.1 0.3 0.5 0.6 0.7 0.9
> with(fm, xyplot(resid(.) ~ carb))



More information about the R-devel mailing list