以下是Dave Tang's Blog on curve fitting
的代码x <- c(32,64,96,118,126,144,152.5,158)
y <- c(99.5,104.8,108.5,100,86,64,35.3,15)
plot(x,y,pch=19)
fit <- lm(y~poly(x,4,raw=TRUE))
summary(fit)
Call:lm(formula = y ~ poly(x, 4, raw = TRUE))
Residuals:
1 2 3 4 5 6 7 8
0.1242 -0.6912 1.6355 1.4491 -5.1240 4.0360 -0.4692 -0.9604
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 7.474e+01 5.473e+01 1.366 0.265
poly(x, 4, raw = TRUE)1 1.426e+00 3.095e+00 0.461 0.676
poly(x, 4, raw = TRUE)2 -2.854e-02 5.729e-02 -0.498 0.653
poly(x, 4, raw = TRUE)3 2.878e-04 4.278e-04 0.673 0.549
poly(x, 4, raw = TRUE)4 -1.134e-06 1.113e-06 -1.018 0.384
Residual standard error: 4.04 on 3 degrees of freedom
Multiple R-squared: 0.9943, Adjusted R-squared: 0.9868
F-statistic: 131.5 on 4 and 3 DF, p-value: 0.001064
鉴于我们认为这非常合适,我想知道拟合的精确多项式方程是什么。有没有办法实现这个目标?
[edit]
另外一个问题,我看到p值都倾向于显示自变量不够显着,但我们看到一个很好的拟合,有人可以解释
答案 0 :(得分:2)
您可以使用包polynomial
中的函数polynom
来编写等式:
library(polynom)
x <- c(32,64,96,118,126,144,152.5,158)
y <- c(99.5,104.8,108.5,100,86,64,35.3,15)
plot(x,y,pch=19)
fit <- lm(y~poly(x,4,raw=TRUE))
p0 <- polynomial(coef(fit))
p0
# 74.73766 + 1.425813*x - 0.0285437*x^2 + 0.0002877714*x^3 - 1.133744e-06*x^4
使用signif
来舍入系数:
p0 <- polynomial(signif(coef(fit), 3))
p0
# 74.7 + 1.43*x - 0.0285*x^2 + 0.000288*x^3 - 1.13e-06*x^4
您可以使用p0
:
f0 <- as.function(p0)
f0(x)
# [1] 99.37580 105.49117 106.86449 98.55089 91.12402 59.96402 35.76922
# [8] 15.96039
predict(fit)
# 1 2 3 4 5 6 7 8
# 99.37580 105.49117 106.86449 98.55089 91.12402 59.96402 35.76922 15.96039
plot(x, y)
lines(x, f0(x), col = "grey", lwd = 2) # bold grey line
lines(x, predict(fit), col = "red", lty = 2) # dashed red line
答案 1 :(得分:1)
摘要中有系数:
f <- function(x) {
return(7.473766e+01 + 1.425813e+00*x -2.854370e-02*x^2 + 2.877714e-04*x^3 - 1.133744e-06*x^4 )
}
plot(x, y)
lines(x, f(x), col="red")