在 R 中,我使用 nls 进行非线性最小二乘拟合。那么如何使用拟合提供的系数值绘制模型函数?

(是的,这是 R 相对新手提出的一个非常幼稚的问题。)

最佳答案

使用 ?nls 中的第一个示例并按照我逐行指出的示例实现以下目标:

#This is just our data frame
DNase1 <- subset(DNase, Run == 1)
DNase1$lconc <- log(DNase1$conc)
#Fit the model
fm1DNase1 <- nls(density ~ SSlogis(lconc, Asym, xmid, scal), DNase1)

#Plot the original points
# first argument is the x values, second is the y values
plot(DNase1$lconc,DNase1$density)

#This adds to the already created plot a line
# once again, first argument is x values, second is y values
lines(DNase1$lconc,predict(fm1DNase1))
predict 参数的 nls 方法会自动返回拟合的 y 值。或者,您添加一个步骤并执行
yFitted <- predict(fm1DNase1)

并将第二个参数中的 yFitted 传递给 lines 。结果如下所示:

或者,如果你想要一个“平滑”的曲线,你所做的就是简单地重复这一点,但在更多点评估函数:
r <- range(DNase1$lconc)
xNew <- seq(r[1],r[2],length.out = 200)
yNew <- predict(fm1DNase1,list(lconc = xNew))

plot(DNase1$lconc,DNase1$density)
lines(xNew,yNew)

关于r - 如何从 R 中的 nls 获取绘图?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9918807/

10-12 14:04