如果您希望预测原始lm
调用中未包含的新 x 值的 y 值,则需要提供 data.frame 参数newdata
。此外,data.frame 的列名需要与模型中使用的变量名相匹配。?predict
没有解释这一点,但在?predict.lm
.
y <- c(0.040, 0.073, 0.87)
x <- c(10.0, 15.0, 20.0)
poly.lm <- lm(y ~ poly(x, 2))
# As DWin noted, predict() will compute fitted y-values using an lm object alone:
all.equal(predict(poly.lm), poly.lm$fitted)
# [1] TRUE
# To predict y for new x-values, make a data.frame:
new.x <- seq(0, 20, 1.0)
new.df <- data.frame(x=new.x)
new.y <- predict(poly.lm, newdata=new.df)
# Unsolicited visualization.
par(mfrow=c(1, 2))
plot(x, y, pch=16, cex=1.6, xlim=c(0, 20), ylim=c(0, 3))
plot(new.x, new.y, col="skyblue", pch=16, cex=1.6, xlim=c(0, 20), ylim=c(0, 3))
points(x, y, cex=1.6)