R nls最佳拟合线-如何强制绘制线?

R nls最佳拟合线-如何强制绘制线?,r,error-handling,nls,R,Error Handling,Nls,我正在尝试编写一个基本函数,用nls将一些最适合的线条添加到绘图中。 除非数据恰好是由传递给nls的公式精确定义的,否则这种方法很有效。我知道这些问题,这是记录在案的行为 然而,我的问题是,我如何才能绕过这个问题,并强制绘制一条最佳拟合线,而不考虑模型准确描述的数据?有没有一种方法可以精确地检测数据匹配并绘制完美拟合的曲线?我目前的狡猾解决方案是: #test data x <- 1:10 y <- x^2 plot(x, y, pch=20) # polynomial line

我正在尝试编写一个基本函数,用nls将一些最适合的线条添加到绘图中。 除非数据恰好是由传递给nls的公式精确定义的,否则这种方法很有效。我知道这些问题,这是记录在案的行为

然而,我的问题是,我如何才能绕过这个问题,并强制绘制一条最佳拟合线,而不考虑模型准确描述的数据?有没有一种方法可以精确地检测数据匹配并绘制完美拟合的曲线?我目前的狡猾解决方案是:

#test data
x <- 1:10
y <- x^2
plot(x, y, pch=20)

# polynomial line of best fit
f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=1, d=1)) 
co <- coef(fit)
curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="red", lwd=2) 
我采用的简单修复方法是稍微抖动数据,但这似乎有点破坏性和黑客行为

# the above code works after doing...
y <- jitter(x^2)
有更好的办法吗?

注意,我必须调整起始值,结果对起始值很敏感

fit <- nlsLM(y ~ f(x,a,b,d), start = c(a=1, b=0.1, d=0.1))

Parameters:
    Estimate Std. Error    t value Pr(>|t|)    
a  1.000e+00  2.083e-09  4.800e+08  < 2e-16 ***
b -7.693e-08  1.491e-08 -5.160e+00  0.00131 ** 
d  1.450e-07  1.412e-08  1.027e+01  1.8e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 6.191e-08 on 7 degrees of freedom

Number of iterations to convergence: 3 
Achieved convergence tolerance: 1.49e-08 

注意,我必须调整起始值,结果对起始值很敏感

fit <- nlsLM(y ~ f(x,a,b,d), start = c(a=1, b=0.1, d=0.1))

Parameters:
    Estimate Std. Error    t value Pr(>|t|)    
a  1.000e+00  2.083e-09  4.800e+08  < 2e-16 ***
b -7.693e-08  1.491e-08 -5.160e+00  0.00131 ** 
d  1.450e-07  1.412e-08  1.027e+01  1.8e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 6.191e-08 on 7 degrees of freedom

Number of iterations to convergence: 3 
Achieved convergence tolerance: 1.49e-08 

尽管如此,在现实世界中,这种情况永远不会发生。总有测量误差。除非你是一名教师,正在进行R考试,并为你的学生提供完美的数据集,那就是:-.@CarlWitthoft我在从Excel导出的数据作为CSV时遇到过这样的问题,因此如果n很小,就舍入到可见数字。@Roland,我想如果你对测试数据舍入不当,即丢失有效的sig图,你得到了你应得的:-@CarlWitthoft好吧,如果你做了适合测量精度的四舍五入,然后用n=4进行回归,这是不应该做的,但这就是生活……尽管如此,在现实世界中,这种情况永远不会发生。总有测量误差。除非你是一名教师,正在进行R考试,并为你的学生提供完美的数据集,那就是:-.@CarlWitthoft我在从Excel导出的数据作为CSV时遇到过这样的问题,因此如果n很小,就舍入到可见数字。@Roland,我想如果你对测试数据舍入不当,即丢失有效的sig图,你得到了你应得的:-@CarlWitthoft好吧,如果你做了适合测量精度的四舍五入,然后用n=4做回归,这是不应该做的,但这就是生活。。。
fit <- nlsLM(y ~ f(x,a,b,d), start = c(a=1, b=0.1, d=0.1))

Parameters:
    Estimate Std. Error    t value Pr(>|t|)    
a  1.000e+00  2.083e-09  4.800e+08  < 2e-16 ***
b -7.693e-08  1.491e-08 -5.160e+00  0.00131 ** 
d  1.450e-07  1.412e-08  1.027e+01  1.8e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 6.191e-08 on 7 degrees of freedom

Number of iterations to convergence: 3 
Achieved convergence tolerance: 1.49e-08