[R] nls and R scoping rules

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jun 10 12:05:51 CEST 2004


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.

-- 
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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list