-->

拟合中的R的函数(Fitting a function in R)

2019-07-30 19:39发布

我有一个似乎有一种对数关系的几个数据点(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")

现在我想找到一个适合的图形,让我推断其他数据点(即最基本的功能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")

后来,我尝试使用,以产生一个拟合模型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

有人能指出我在什么从这里做正确的方向?

跟进

阅读您的意见和周围有点谷歌搜索后,我进一步调整启动参数abc然后突然模型收敛。

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)

Answer 1:

也许使用模型立方规范,并通过估计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.



Answer 2:

尝试把你的反应变量的日志,然后使用lm以适应线性模型:

fit <- lm(log(y) ~ x, data=mydata)

调整后的R平方为0.8486,其中面值不坏。 你可以看一下配合使用的情节,例如:

plot(fit, which=2)

但或许,这毕竟不是这样一个不错的选择:

last_plot() + geom_line(aes(x=x, y=exp(fit$fitted.values)))


Answer 3:

检查这个文件出来: http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf

简而言之,首先你需要在模型上决定,以适应到您的数据(例如,指数),然后估算它的参数。

下面是一些广泛使用的发行版: http://www.itl.nist.gov/div898/handbook/eda/section3/eda366.htm



文章来源: Fitting a function in R