Exponential fitting with R

不羁岁月 提交于 2019-12-13 00:55:25

问题


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.


回答1:


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(...).



来源:https://stackoverflow.com/questions/32251853/exponential-fitting-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!