# [R] bug in nls?

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jun 26 14:33:20 CEST 2008

```Try this and note, in particular, that the "model:" line
in the output has the correct variables substituted:

> nm <- names(DF)
> eqn <- sprintf("%s ~ a * %s", nm[2], nm[1])
> nls(eqn, DF, start = c(a = 1))
Nonlinear regression model
model:  y ~ a * x
data:  DF
a
1.133
residual sum-of-squares: 31.51

Number of iterations to convergence: 1
Achieved convergence tolerance: 1.55e-10

On Thu, Jun 26, 2008 at 7:57 AM, Petr PIKAL <petr.pikal at precheza.cz> wrote:
> Dear all
>
> Nobody responded to my previous post so far so I try with more offending
> subject.
>
> I just encountered a strange problem with nls formula. I tried to use nls
> in cycle but I was not successful. I traced the problem to some parse
> command.
>
> Here is an example
>
> DF<-data.frame(x=1:10, y=3*(1:10)^.5+rnorm(10))
>
> coef(lm(log(DF[,2])~log(DF[,1])))
>  (Intercept) log(DF[, 1])
>   0.7437320    0.6831726
> # this works
>
> coef(nls(y~a*x^b, data=DF, start=list(a=3, b=.7)))
>        a         b
> 2.6412881 0.5545907
> # OK, this works too
>
> coef(nls(DF[,2]~a*DF[,1]^b, data=DF, start=list(a=3, b=.7)))
> Error in parse(text = x) : unexpected end of input in "~ "
> coef(nls(DF[,2]~a*DF[,1]^b, start=list(a=3, b=.7)))
> Error in parse(text = x) : unexpected end of input in "~ "
> # but this does not
>
>
> Browse[1]>
> debug: mf\$formula <- as.formula(paste("~", paste(varNames[varIndex],
>    collapse = "+")), env = environment(formula))
> Browse[1]>
> Error in parse(text = x) : unexpected end of input in "~ "
>>
>
> Actually the problem is that with calling nls with DF[,n]~... varNames and
> varIndex is not correctly specified.
>
> I am not sure if this behaviour is a bug or feature. If it is a feature,
> please help me how to call variables from data frame
> when using nls inside cycle
>
> for (i in ....) result[i,] <- coef(nls( ...., ))
>
> Thank you
> Petr
>
>> sessionInfo()
> R version 2.8.0 Under development (unstable) (2008-05-18 r45723)
> i386-pc-mingw32
>
> locale:
> LC_COLLATE=Czech_Czech Republic.1250;LC_CTYPE=Czech_Czech
> Republic.1250;LC_MONETARY=Czech_Czech
> Republic.1250;LC_NUMERIC=C;LC_TIME=Czech_Czech Republic.1250
>
> attached base packages:
> [1] stats     grDevices datasets  utils     graphics  methods   base
>
> other attached packages:
> [1] nlme_3.1-88    lattice_0.17-7 fun_0.1
>
> loaded via a namespace (and not attached):
> [1] grid_2.8.0  tools_2.8.0
>
>
> Petr Pikal
> petr.pikal at precheza.cz
> 724008364, 581252140, 581252257
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

```