我不知道如何用原始loess
函数做预测带,但是包loess.sd
中有一个函数可以做到这一点!从文档中几乎逐字记录:msir
msir
library(msir)
data(cars)
# Calculates and plots a 1.96 * SD prediction band, that is,
# a 95% prediction band
l <- loess.sd(cars, nsigma = 1.96)
plot(cars, main = "loess.sd(cars)", col="red", pch=19)
lines(l$x, l$y)
lines(l$x, l$upper, lty=2)
lines(l$x, l$lower, lty=2)
你的第二个问题有点棘手,因为loess.sd
它没有预测函数,但你可以通过线性插值预测的平均值和你得到的标准差loess.sd
(使用approx
)来破解它。反过来,这些可用于使用具有预测均值和 SD 的正态分布来模拟数据:
# Simulate x data uniformly and y data acording to the loess fit
sim_x <- runif(100, min(cars[,1]), max(cars[,1]))
pred_mean <- approx(l$x, l$y, xout = sim_x)$y
pred_sd <- approx(l$x, l$sd, xout = sim_x)$y
sim_y <- rnorm(100, pred_mean, pred_sd)
# Plots 95% prediction bands with simulated data
plot(cars, main = "loess.sd(cars)", col="red", pch=19)
points(sim_x, sim_y, col="blue")
lines(l$x, l$y)
lines(l$x, l$upper, lty=2)
lines(l$x, l$lower, lty=2)