我有一些数据点(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)
最佳答案
也许对您的模型使用三次规范并通过 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.
关于r - 在 R 中拟合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11844522/