我有一些似乎具有对数关系的数据点(x 和 y)。
> mydata
x y
1 0 123
2 2 116
3 4 113
4 15 100
5 48 87
6 75 84
7 122 77
> qplot(x, y, data=mydata, geom="line")
现在我想找到一个适合该图的基础函数,并允许我推断其他数据点(即3
或82
)。我读过lm
,nls
但我真的没有得到任何地方。
起初,我创建了一个我认为最像情节的函数:
f <- function(x, a, b) {
a * exp(b *-x)
}
x <- seq(0:100)
y <- f(seq(0:100), 1,1)
qplot(x,y, geom="line")
之后,我尝试使用以下方法生成拟合模型nls
:
> fit <- nls(y ~ f(x, a, b), data=mydata, start=list(a=1, b=1))
Error in numericDeriv(form[[3]], names(ind), env) :
Missing value or an Infinity produced when evaluating the model
有人可以指出我从这里做什么的正确方向吗?
跟进
在阅读了您的评论并进一步搜索后,我调整了 的起始参数a
,b
然后c
模型突然收敛。
fit <- nls(y~f(x,a,b,c), data=data.frame(mydata), start=list(a=1, b=30, c=-0.3))
x <- seq(0,120)
fitted.data <- data.frame(x=x, y=predict(fit, list(x=x))
ggplot(mydata, aes(x, y)) + geom_point(color="red", alpha=.5) + geom_line(alpha=.5) + geom_line(data=fitted.data)