r - 在 R 中拟合函数

标签 r curve-fitting lm nls

我有一些数据点(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")

plot

现在我想找到一个适合该图并允许我推断其他数据点的基础函数(即 382 )。我读过 lmnls但我真的一事无成。

起初,我创建了一个我认为它最像情节的函数:
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")

plot2

之后,我尝试使用 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 的起始参数。 , bc然后模型突然收敛了。
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)

plot3

最佳答案

也许对您的模型使用三次规范并通过 lm 进行估计会给你一个很好的配合。

# Importing your data
dataset <- read.table(text='
    x   y
1   0 123
2   2 116
3   4 113
4  15 100
5  48  87
6  75  84
7 122  77', header=T)

# I think one possible specification would be a cubic linear model
y.hat <- predict(lm(y~x+I(x^2)+I(x^3), data=dataset)) # estimating the model and obtaining the fitted values from the model

qplot(x, y, data=dataset, geom="line") # your plot black lines
last_plot() + geom_line(aes(x=x, y=y.hat), col=2) # the fitted values red lines

# It fits good.

enter image description here

关于r - 在 R 中拟合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11844522/

相关文章:

math - 寻找曲线的公式

python - 使用 curve_fit 限制高斯拟合

r - 关于使用R进行时间序列自动拟合的问题

r - R : plm vs lm + factor() 中的固定效果

objective-c - Xcode - OpenEars 语言模型文件错误

r - 如何向基于 lm 的弹性表添加列

r - 如何使用 RDCOMClient 从辅助帐户发送 Outlook 电子邮件 - 翻译现有的 VBA 代码?

r - 在 R 上计算基于五分位数的分数

r - lm() 函数;提取截距的统计显着性;存储在变量中

r - 将每个数据框行文本分成五个均匀的文本 block