[R] Different result from nls in R-2.2.1 and R-2.3.1

Frede Aakmann Tøgersen FredeA.Togersen at agrsci.dk
Thu Sep 21 09:02:03 CEST 2006

```
Short story: January 2006 I did some analysis in R-2.2.1 using nls. Repeating the exercise in R-2.3.1 yesterday produced somewhat different results.

After some debugging I found that either nls is the problem or that mine understanding of environments or scoping rules is lacking something.

This is a short reproducing example.

x <- seq(0,5,len=20)

n <- 1
y <- 2*x^2 + n + rnorm(x)

xy <- data.frame(x=x,y=y)

myf <- function(x,a,b,n){
res <- a*x^b + n
## a print for debugging purpose
print(n)
res
}

## This works as I expect it to do in R-2.2.1 but doesn't work in R-2.3.1.
## n is somehow sat to nrow(xy) inside nls()
## Note that x and y is defined in the dataframe xy, whereas n is found in the global environment.
fit <- nls(y ~ myf(x,a,b,n), data=xy, start=c(a=1,b=1), trace=TRUE)

## this works in both versions
## x,y,n found in the .GlobalEnv
fit <- nls(y ~ myf(x,a,b,n), start=c(a=1,b=1), trace=TRUE)

## this works in both versions.
## x, y, n found in dataframe xyn
xyn <- data.frame(xy,n=n)
fit <- nls(y ~ myf(x,a,b,n), data=xyn, start=c(a=1,b=1), trace=TRUE)

## this works in both versions
## Now using the variable .n instead of n
## .n is found in .GlobaEnv
.n <- 1
fit <- nls(y ~ myf(x,a,b,.n), data=xy, start=c(a=1,b=1), trace=TRUE)

In my real case and the example above, I do have three or more parameters of which fitting is done only on few of theme. Is this a problem? Or should I ask, why is this a problem in R-2.3.1 but not in R-2.2.1?

Is my problem related to this difference between lines of code from nls:

R-2.2.1:     mf <- as.list(eval(mf, parent.frame()))

R-2.3.1:     mf <- eval.parent(mf)
n <- nrow(mf)
mf <- as.list(mf)

where n is being defined in the scope of nls in the latest version?

Best regards

Frede Aakmann Tøgersen

Danish Institute of Agricultural Sciences
Research Centre Foulum
Dept. of Genetics and Biotechnology
Blichers Allé 20, P.O. BOX 50
DK-8830 Tjele

Phone:   +45 8999 1900
Direct:  +45 8999 1878

E-mail:  FredeA.Togersen at agrsci.dk
Web:	   http://www.agrsci.org

This email may contain information that is confidential.
Any use or publication of this email without written permission from DIAS is not allowed.
If you are not the intended recipient, please notify DIAS immediately and delete this email.

```