[R] nls and R scoping rules

Luke Tierney luke at stat.uiowa.edu
Thu Jun 10 14:39:11 CEST 2004


On Thu, 10 Jun 2004, Prof Brian Ripley wrote:

> On Thu, 10 Jun 2004, Prof Brian Ripley wrote:
> 
> > Around R 1.2.x the notion was introduced that variables should be looked 
> > for in the environment of a formula.  Functions using model.frame got 
> > converted to do that, but nls did not.  I guess that the best way forward 
> > is to ensure that nls (and nlsModel) does search the environment of the 
> > formula for functions.
> 
> It transpires that is rather easy to achieve.  At the top of nlsModel and 
> nlsModel.plinear use
> 
>     env <- new.env(parent=environment(form))
> 
> instead of
> 
>     env <- new.env()
> 
> This then automatically searches for objects used in the formula
> 
> Notes
> 
> 1) nls is in a namespace, so you need to fix the copy in the namespace or 
> fix the source code and rebuild.
> 
> 2) This will add to the baggage needed when you save() a nls fit in a 
> workspace.  I think that is inevitable as we cannot just identify the 
> funtions used in the formula (as they might call other functions in the 
> local environment), and it is necessary to capture the objects needed to 
> evaluate the formula for the predict() method to be reliable.
> 
> We could call all.names() to get the names of functions used directly in 
> the formula, but that seems not good enough (previous para).
> 
> Question to the cognescenti: is the price in 2) too great for this to be 
> done for 1.9.1?  I will put the change in R-devel for now.

I don't think so.  The fit objects already contain the formula (via
the environment of the functions in the structure).  Since environment
sharing is preserved within a serialization, this means the change
would only alter the parent of the env environment, not add anything
extra.

Best,

luke


-- 
Luke Tierney
University of Iowa                  Phone:             319-335-3386
Department of Statistics and        Fax:               319-335-3017
   Actuarial Science
241 Schaeffer Hall                  email:      luke at stat.uiowa.edu
Iowa City, IA 52242                 WWW:  http://www.stat.uiowa.edu




More information about the R-help mailing list