我已经拟合了一个简单的自然样条(df = 3)模型,现在想对一些样本外的观测值进行预测。使用 predict()
函数,我可以得到样本内观测值的拟合值,但是我无法得到新观测值的预测值。
以下是我的代码:
library(splines)
set.seed(12345)
x <- seq(0, 2, by = 0.01)
y <- rnorm(length(x)) + 2*sin(2*pi*(x-1/4))
# My n.s fit:
fit.temp <- lm(y ~ ns(x, knots = seq(0.01, 2, by = 0.1)))
# Getting fitted values:
fit.temp.values <- predict(fit.temp,interval="prediction", level = 1 - 0.05)
# Plotting the data, the fit, and the 95% CI:
plot(x, y, ylim = c(-6, +6))
lines(x, fit.temp.values[,1], col = "darkred")
lines(x, fit.temp.values[,2], col = "darkblue", lty = 2)
lines(x, fit.temp.values[,3], col = "darkblue", lty = 2)
# Consider the points for which we want to get the predicted values:
x.new <- c(0.275, 0.375, 0.475, 0.575, 1.345)
如何获取x.new的预测值?
非常感谢您的帮助,
p.s. 我在SO上搜了所有相关问题,但没有找到答案。
predict()
函数来获取外样本观测值的预测值。 - Sam?predict.lm
。 - Roland