我有一个简单的自然样条(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)
Run Code Online (Sandbox Code Playgroud)
如何获得x.new的预测值?
非常感谢您的帮助,
ps我在SO上搜索了所有相关问题,但我找不到答案.
使用名为的列创建数据框x,并将其作为newdata参数传递给predict:
predict(fit.temp, newdata=data.frame(x=x.new))
Run Code Online (Sandbox Code Playgroud)