1

I have a dataset like this

df

x          y 
7.3006667 -0.14383333
-0.8983333  0.02133333
2.7953333 -0.07466667

and I would like to fit an exponential function like y = a*(exp(bx)).

This is what I tried and the error I get

f <- function(x,a,b) {a * exp(b * x)}
st <- coef(nls(log(y) ~ log(f(x, a, b)), df, start = c(a = 1, b = -1)))

Error in qr.qty(QR, resid) : NA/NaN/Inf in foreign function call (arg 5)
In addition: Warning messages:
1: In log(y) : NaNs produced
2: In log(y) : NaNs produced

fit <- nls(y ~ f(x, a, b), data = df, start = list(a = st[1], b = st[2]))

Error in nls(y ~ exp(a + b * x), data = df, start = list(a = st[1],  : 
  singular gradient

I believe it has to do with the fact that the log is not defined for negative numbers but I don't know how to solve this.

user3036416
  • 1,205
  • 2
  • 15
  • 28
  • Sounds like you have a model/data incompatibility issue, not a programming or model convergence issue. – davechilders Aug 27 '15 at 14:38
  • If `a` is positive then the right hand side can never equal a negative `y` and if `a` is negative then the right hand side can never equal a positive `y` so this model seems inconsistent with data that has both positive and negative y values as in your data set. Furthermore, one cannot take the log of `y` since some components of `y` are negative. Suggest you try a different model if that is indeed your data. – G. Grothendieck Aug 27 '15 at 15:01
  • @G.Grothendieck the problem is that I don't understand which model can I use to simulate an exponential.. – user3036416 Aug 27 '15 at 15:27

1 Answers1

2

I'm having trouble seeing the problem here.

f <- function(x,a,b) {a * exp(b * x)}
fit <- nls(y~f(x,a,b),df,start=c(a=1,b=1))
summary(fit)$coefficients
#      Estimate Std. Error    t value  Pr(>|t|)
# a -0.02285668 0.03155189 -0.7244157 0.6008871
# b  0.25568987 0.19818736  1.2901422 0.4197729

plot(y~x, df)
curve(predict(fit,newdata=data.frame(x)), add=TRUE)

The coefficients are very poorly estimated, but that's not surprising: you have two parameters and three data points.

As to why your code fails: the first call to nls(...) generates an error, so st is never set to anything (although it may have a value from some earlier code). Then you try to use that in the second call to nls(...).

jlhoward
  • 58,004
  • 7
  • 97
  • 140