[R] matching of arguments in ...?

Thomas Lumley tlumley at u.washington.edu
Wed Nov 5 16:16:23 CET 2003


On Wed, 5 Nov 2003, David Firth wrote:

> I am puzzled by this (with R --vanilla):
>
>    > test <- function(formula, ...) lm(formula, ...)
>    > test(1:4 ~ 1, offset=rep(1,4))
>    Error in eval(expr, envir, enclos) : ..1 used in an incorrect
> context, no ... to look in
>    >  test(1:4 ~ 1, weights=rep(1,4))
>    Error in eval(expr, envir, enclos) : ..1 used in an incorrect
> context, no ... to look in
>    >  test(1:4 ~ 1, x=TRUE)
>
>    Call:
>    lm(formula = formula, x = TRUE)
>
>    Coefficients:
>    (Intercept)
>            2.5
>
> Some arguments (such as x) seem to pass willingly through ..., while
> others (such as offset and weights) do not.  Same thing happens with
> glm.  I haven't experimented more widely.
>
> Can some kind soul offer an explanation?

This is a historical legacy of someone trying to be too helpful.

In lm() and similar functions there are some arguments that are
interpreted as if they were quoted expressions and then are looked up in
data= and in the calling frame (actually in environment(formulas)).

So

 lm(y~x, offset=z, data=df)

will work if z is either a column of df or a variable floating free in the
calling frame.

In order to make this rather unnatural evaluation work, lm and model.frame
have to play tricks with these arguments: they are explicitly evaluated in
environment(formula), in this case the environment inside test().

This sort of thing is why some of us strongly recommend not having
implicit dynamic scoping on new modelling functions, so eg in the survey
package the syntax looks like
  svydesign(id=~id, weights=~w, data=df)
with explicit formulas.  The other option is explicitly quoted
expressions.


	-thomas




More information about the R-help mailing list