为了扩展我上面的评论,这里是一个使用 mtcars 数据集的示例,其中我们拟合了 mpg = beta0 + beta1 * disp 形式的线性模型。
fit <- lm(mpg ~ disp, data = mtcars)
summary(fit)
#
#Call:
#lm(formula = mpg ~ disp, data = mtcars)
#
#Residuals:
# Min 1Q Median 3Q Max
#-4.8922 -2.2022 -0.9631 1.6272 7.2305
#
#Coefficients:
# Estimate Std. Error t value Pr(>|t|)
#(Intercept) 29.599855 1.229720 24.070 < 2e-16 ***
#disp -0.041215 0.004712 -8.747 9.38e-10 ***
#---
#Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 3.251 on 30 degrees of freedom
#Multiple R-squared: 0.7183, Adjusted R-squared: 0.709
#F-statistic: 76.51 on 1 and 30 DF, p-value: 9.38e-10
我们为disp 生成一些新数据,并使用模型系数来预测mpg 的响应。
df <- data.frame(disp = seq(1, 1000, length.out = 20))
df$mpg <- predict(fit, newdata = df)
我们现在将相同的模型拟合到新数据。
fit.new <- lm(mpg ~ disp, data = df)
#
#Call:
#lm(formula = mpg ~ disp, data = df)
#
#Residuals:
# Min 1Q Median 3Q Max
#-1.720e-14 -3.095e-15 1.302e-15 3.618e-15 5.719e-15
#
#Coefficients:
# Estimate Std. Error t value Pr(>|t|)
#(Intercept) 2.960e+01 2.235e-15 1.325e+16 <2e-16 ***
#disp -4.122e-02 3.819e-18 -1.079e+16 <2e-16 ***
#---
#Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 5.178e-15 on 18 degrees of freedom
#Multiple R-squared: 1, Adjusted R-squared: 1
#F-statistic: 1.165e+32 on 1 and 18 DF, p-value: < 2.2e-16
#
#Warning message:
#In summary.lm(fit.new) : essentially perfect fit: summary may be unreliable
注意估计值是如何相同的(但标准差和 t 统计量不同!)。另请注意第二个模型拟合底部的警告。
更新
如果您有系数 beta0 和 beta1,只需将响应计算为
beta0 <- coef(fit)[1]
beta1 <- coef(fit)[2]
df <- data.frame(disp = seq(1, 1000, length.out = 20))
df$mpg <- beta0 + df$disp * beta1