[R] match.call() and do.call()

Prof Brian D Ripley ripley at stats.ox.ac.uk
Sat Feb 10 10:26:27 CET 2001


On Fri, 9 Feb 2001, Peter Perkins wrote:

> hi all -
>
> i have a function that needs to call glm() with a weights argument that
> includes a variable whose name comes from the caller.  so instead of:
>
>    fit <- glm(formula, poisson(), data, weights = 1-z, ...),
>
> i do something like this:
>
>    fit <- do.call("glm", list(formula=formula, family=poisson(),
>       data=data, weights = call("-", 1, as.name(zname)), ...))
>
> this works ok, but i find that the call component of the fit object
> returned by glm() has taken things a bit too literally -- it has
> literals for all of the args in the call, rather than variable and
> function names as the object returned by the first form above would.  in
> a simpler example,
>
> > fun <- function(x, f) print(match.call())
> > xx <- 1:10
> > fun(x, sum)
> fun(x = x, f = sum)
> > do.call("fun", list(x = xx, f = sum))
> fun(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), f = function (...,
>     na.rm = FALSE)
> .Internal(sum(..., na.rm = na.rm)))
>
> this sure is ugly -- can anyone offer a way to get around it?  that is,
> i'd like to have fit$call look like it would for a direct call to glm(),
> with the user-supplied variable name nicely substituted into the
> weights= arg.  as i understand it, i can't get around using do.call().

You need to quote the arguments you do not want literally in a call to
do.call, so

do.call("fun", list(x = quote(xx), f = quote(sum)))

works as you expected.


However, I think you are using the wrong tool.  Try substitute:

eval(substitute(glm(formula, poisson(), data, weights=1-w),
                list(w=as.name(zname))))

if zname is a character vector.

Also, one can construct a call as a character string and use
eval(parse(text=)), although substitute is usually cleaner.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list