R语言二次函数曲线拟合教程:实战案例与可视化
假设我们有以下数据集:
x <- 1:10
y <- c(2, 5, 9, 15, 23, 33, 45, 59, 75, 93)
我们可以使用 lm() 函数拟合二次函数曲线:
fit <- lm(y ~ poly(x, 2, raw = TRUE))
其中,poly(x, 2, raw = TRUE) 表示使用 $x$ 的二次多项式进行拟合,raw = TRUE 表示不对 $x$ 进行标准化处理。
我们可以使用 summary() 函数查看拟合结果:
summary(fit)
输出结果:
Call:
lm(formula = y ~ poly(x, 2, raw = TRUE))
Residuals:
1 2 3 4 5 6 7 8
-0.053333 -0.386667 -0.360000 0.546667 0.040000 0.013333 -0.426667 0.080000
9 10
0.493333 -0.013333
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.88000 1.63035 0.540 0.6133
poly(x, 2, raw = TRUE)1 2.29000 0.39056 5.861 0.00152 **
poly(x, 2, raw = TRUE)2 0.90000 0.03906 23.005 1.5e-07 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.4839 on 7 degrees of freedom
Multiple R-squared: 0.9887, Adjusted R-squared: 0.9865
F-statistic: 449.8 on 2 and 7 DF, p-value: 1.096e-07
拟合结果包括拟合系数、标准误差、t 值、显著性水平、残差标准误差、$R^2$ 值等指标。我们可以使用 plot() 函数绘制拟合结果:
plot(x, y)
lines(x, predict(fit), col = 'red')
结果如下图所示:

原文地址: https://www.cveoy.top/t/topic/mHuF 著作权归作者所有。请勿转载和采集!