【发布时间】:2012-08-04 09:11:10
【问题描述】:
我有几个似乎具有对数关系的数据点(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
有人能指出我从这里做什么的正确方向吗?
跟进
在阅读了您的 cmets 并进一步搜索后,我调整了 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)
【问题讨论】:
-
我认为正确的指向你的地方是统计 101 课程。你至少可以通过
lm向我们展示你的努力。 -
我建议您阅读 R 手册:在您的 RConsole 中输入
?lm、?nls和?formula -
抱歉我的懒惰 - 我现在有点沮丧。我添加了我对
nls执行的步骤以及它产生的错误。 -
我知道这是一个老问题,但你们每个人都试过使用
lm(y ~ poly(x, 3), data = mydata)吗?可以尝试不同次数的多项式,并使用anova比较lm的结果。 -
请编辑您的问题 - 您现在指的是未定义的
f(x,a,b,c)。它是什么?你只有f(x,a,b)
标签: r curve-fitting lm nls