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

Marc Girondot marc.girondot at u-psud.fr
Thu Feb 12 11:09:48 CET 2009

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:

First without stochasticity (it is a dummy example, the fited value is
simple the mean of a set of 10 numbers):

#Ten numbers
x <- 1:10
#Generate 10 Gaussian random number with mean=3 sd=1
simy <- rnorm(length(x), mean=3, sd=1)
#theoretical value for each of the 10 numbers=the adjust value
y1 <- function(pp,xx) {rep(pp$a, length(xx))}
resid <- function(pp,observed,xx) {observed-y1(pp,xx)}
#Starting parameter
pStart <- list(a=0.1)
#non-linear fit
nls.lm.test <- nls.lm(par=pStart, fn=resid, observed=simy, xx=x,

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
y1 <- function(pp,xx) {rep(pp$a, length(xx))+rnorm(length(xx), mean=0,

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

Has someone a solution ?
Thanks a lot

[we use previously Profit software (macosx software) for such a fit and it
works there. But r is more portable and we will prefer to use it. Thanks]

More information about the R-help mailing list