From tlumley at u.washington.edu  Sat Nov 19 01:35:45 2005
From: tlumley at u.washington.edu (Thomas Lumley)
Date: Fri, 18 Nov 2005 16:35:45 -0800 (PST)
Subject: [Rd] A problem with glm() and possibly model-using functions in
 general?
In-Reply-To: <1FB5B939-D81E-4CC6-9806-C4D1912581F7@stat.harvard.edu>
References: <1FB5B939-D81E-4CC6-9806-C4D1912581F7@stat.harvard.edu>
Message-ID: <Pine.LNX.4.63a.0511181631510.14137@homer22.u.washington.edu>

On Fri, 18 Nov 2005, Byron Ellis wrote:

> So, consider the following:
>
> > example(glm)
> > g = function(model) { w = runif(9);glm(model,weights=w); }
> > g(counts ~ outcome + treatment)
> Error in eval(expr, envir, enclos) : object "w" not found
>
> Huh?! I suspect that somebody is lazily evaluating arguments in the
> wrong environment (probably GlobalEnv in this case). I'm willing to
> accept the fact that there's some mysterious reason you'd actually
> want this behavior, but this looks like it should be filed as a bug
> to me.

Yes, there is a reason you'd actually want this behaviour, and 
it is documented. In help(model.frame) it says

      All the variables in 'formula', 'subset' and in '...' are looked
      for first in 'data' and then in the environment of 'formula' (see
      the help for 'formula()' for further details) and collected into a
      data frame.

In your example the environment of 'formula' is the global environment, 
since that's where it was created.

There isn't a set of scoping rules for formulas that will make everyone 
happy, but this lexical scope is what R has done for quite some time.

 	-thomas



[Rd] A problem with glm() and possibly model-using functions in general?
Thomas Lumley