1

I trying to fit a exponential model to some pre-computed data using the function nls in r. However, data that is computed and fits exactly to my model cannot be fitted by nls, while it works with data that is slightly off. Now I'm wondering, if I am doing something wrong...

Here's a sample code with what is not working:

times <- c(0,10,20,30,40,50,60)
A3 <- data.frame(time=times, intensity=c(0))
# calculating some optimal data:
A3$intensity <- 200*exp(-0.022*A3$time)

# do the fitting:
nls(data=A3, formula=intensity~200*exp(b * time), start=c(b=-0.022))

As you can see I'm passing the exact same formula to nls that I used to calculate the data. Additionally I pass the exact coefficient to nls. Still it is not able to fit the data to the model... But instead it tells me that the number of iterations is exceeded (which is 50).

However, if I manipulate my data so that the intensity is slightly off, suddenly it works.

A3p1 <- A3
#increasing the intensities by 1
A3p1$intensity <- A3p1$intensity + 1

nls(data=A3p1, formula=intensity~200*exp(b * time), start=c(b=-0.022))

In this case it is working and even returns a coefficient that is close enough: -0.02167

Can anyone explain me, why that is happening and how I need to adjust my code to get proper results?

Matthias
  • 11
  • 1
  • The `?nls` help page has the following warning: "Do not use nls on artificial 'zero-residual' data." You can check that out for more info. – MrFlick Apr 30 '19 at 14:03
  • Thank you for these comments. That actually explains it. Although, it doesn't solve a problem on top of that regarding a trendline in ggplot2. Does it make sense to modify this question to adress that problem, or should I open another question? – Matthias Apr 30 '19 at 14:22
  • That would be a big change; you should open a different question. But the problem will be the same. You can't use `nls` for perfect fit data. You'd need to use something like `lm()` as in the duplicate. – MrFlick Apr 30 '19 at 14:28
  • Okay. Thank you! – Matthias Apr 30 '19 at 14:56

0 Answers0