绘制自举的置信区间

时间:2019-05-12 14:59:30

标签: r confidence-interval statistics-bootstrap

我正在尝试绘制自举线性模型,我想包括模型的上下置信区间,并且不确定我是否正确计算了自举上限和下限。以下是结合使用cars库中的r中的boot数据集的示例。

library(boot)


plot(speed~dist,cars,pch=21,bg="grey")
## standard linear model
mod<-lm(speed~dist,cars)
new.dat=seq(0,120,10)
mod.fit<-predict(mod,newdata=data.frame(dist=new.dat),interval="confidence")

lines(new.dat,mod.fit[,1]);#line fit
lines(new.dat,mod.fit[,2],lty=2);#lower confidence interval
lines(new.dat,mod.fit[,3],lty=2);#upper confidence interval

##Bootstrapped Confidence Intervals
lm.boot=function(formula, data, indices) {
  d <- data[indices,] # allows boot to select sample 
  fit <- lm(formula, data=d)
  return(coef(fit)) 
}

results <- boot(data=cars, statistic=lm.boot, 
                R=100, formula=speed~dist)
N.mod<-nrow(cars)
x.val<-new.dat
y.boot.fit<-(mean(results$t[,2])*x.val)+mean(results$t[,1])
y.boot.fit.uCI<-y.boot.fit+qt(0.975,N.mod-2)*sd(results$t[,2])
y.boot.fit.lCI<-y.boot.fit-qt(0.975,N.mod-2)*sd(results$t[,2])

lines(new.dat,y.boot.fit,col="red")
lines(new.dat,y.boot.fit.lCI,lty=2,col="red");#lower confidence interval
lines(new.dat,y.boot.fit.uCI,lty=2,col="red");#upper confidence interval

legend("bottomright",legend=c("Linear Model","Bootstrapped Model"),lty=1,
col=c("black","red"),ncol=1,cex=1,bty="n",y.intersp=1.5,x.intersp=0.75,
xpd=NA,xjust=0.5)

使用此代码,我得到以下输出,其中自举置信区间位于自举拟合线的顶部。

linear model examples

感谢任何帮助/指导。当然,这可能更适合交叉验证或其他统计专用板。

0 个答案:

没有答案