# [R] Using nls or nls.lm with a simulation output

Dieter Menne dieter.menne at menne-biomed.de
Thu Feb 12 14:55:38 CET 2009

```Marc Girondot <marc.girondot <at> u-psud.fr> writes:

>
> We would like to fit parameters using a simulation with stochastic
> processes as theoretical values. We generate a simple exemple with nls.lm
> to see the logic and the problem:
>
Example removed
...
> pStart <- list(a=0.1)

> #non-linear fit
> library(minpack.lm)
> nls.lm.test <- nls.lm(par=pStart, fn=resid, observed=simy, xx=x,
> control=nls.lm.control(nprint=1))
>
> It works fine:
> It.    0, RSS =    86.2811, Par. =        0.1
> It.    1, RSS =    5.69735, Par. =    2.93873
> It.    2, RSS =    5.69735, Par. =    2.93873
>
> Now let the function generating the theoretical values returns also a
> little bit noise, as observed from the output of a simulation with
> stochasticity:
> y1 <- function(pp,xx) {rep(pp\$a, length(xx))+rnorm(length(xx), mean=0,
> sd=0.01)}
>
> Then the fit failed:
> It.    0, RSS =    86.1011, Par. =        0.1
> It.    1, RSS =    86.4468, Par. =        0.1
>
> Similar problem is observed for nls

Thanks for the working example. When I tried to use a start parameter
closer to 3, convergence was achieved. This is one of the relatively
rare cases (on this list) where the start parameter(s) matter(s). In most
cases, non-linear fits fails because they are hopelessly over-parameterized.

Gabor Grothendiek's package nls2 might help here.

Dieter

```