[R] Scoping and nls.

Rolf Turner rolf at math.unb.ca
Tue Oct 26 00:42:33 CEST 2004

A colleague of mine is trying to use nls() to effect an optimization,
and is encountering a scoping problem.  I should know how to solve it
for him but .... well, I just don't.

I also had a quick scrounge of the archives --- I know I've seen this
topic addressed before --- but I couldn't track it down.

So here's a toy example that demonstrates the problem:

hhh <- function(y,x) {
        g <- function(a,b,x) {1/(1+a^2 + b^2*exp(x))}
x <- runif(50,1,10)
y <- 1/(1+16 + 36*exp(x)) + rnorm(50,0,0.1)

which results in an error

	Error in get(x, envir, mode, inherits) : variable "g" was not found

So can one assign the function ``g'' somewhere where it **can**
be found?  I.e. use something like


Or is there some other magic incantation that can be used here
to get nls to deal with a ``g'' defined inside the function
which call nsl()?

In the real problem the function g is a complicated gadget, taking
different forms in different parts of its domain, so it is
inconvenient-to-impossible to specify it explicitly in the formula in
the call to nls().

Thanks for any help you can give.


					Rolf Turner
					rolf at math.unb.ca

More information about the R-help mailing list