对单个统计量使用自助法
以mtcars数据集为例,它包含32辆汽车的信息。假设我们正使用多元回归根据车重(1b/1000)和发动机排量(cu.in,即立方英寸)来预测汽车每加仑形式的英里数,除了标准的回归统计量,我们还想获得95%的R平方值的置信区间,那么便可使用非参数的自助法来获取置信区间。
首要任务是编写一个获取R平方值的函数:
rsq <- function(formula, data, indices){
d <- data[indices,]
fit <- lm(formula, data=d)
return (summary(fit)$r.square)
}
函数返回回归的R平方值。d<-data[indices,]必须声明,因为boot()要用其来选择样本,下面对R平方值使用自助法,代码如下:
> #dui dan ge tong ji liang shi yong zi zhu fa
> library(boot)
> set.seed(1234)
> results <- boot(data=mtcars, statistic = rsq, R=1000, formula=mpg~wt+disp)
> print(results)
ORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = mtcars, statistic = rsq, R = 1000, formula = mpg ~
wt + disp)
Bootstrap Statistics :
original bias std. error
t1* 0.7809306 0.0133367 0.05068926
> plot(results)
通过上图可以知道,自主的R平方值不呈正态分布,它的95%的置信区间可以通过以下代码获得:
> boot.ci(results, type = c("perc","bca"))
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 1000 bootstrap replicates
CALL :
boot.ci(boot.out = results, type = c("perc", "bca"))
Intervals :
Level Percentile BCa
95% ( 0.6838, 0.8833 ) ( 0.6344, 0.8549 )
Calculations and Intervals on Original Scale
Some BCa intervals may be unstable
对多个统计量使用自助法
依然以mtcars数据集为例,我们获取一个统计量向量——三个回归系数(截距项、车重和发动机排量)95%的置信区间:
> bs <- function(formula, data, indices){
+ d <- data[indices,]
+ fit <- lm(formula, data=d)
+ return (coef(fit))
+ }
> library(boot)
> set.seed(1234)
> results <- boot(data = mtcars, statistic = bs, R=1000, formula=mpg~wt+disp)
> print(results)
ORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = mtcars, statistic = bs, R = 1000, formula = mpg ~
wt + disp)
Bootstrap Statistics :
original bias std. error
t1* 34.96055404 0.1378732942 2.485756673
t2* -3.35082533 -0.0539040965 1.170427539
t3* -0.01772474 -0.0001208075 0.008786803
当对多个统计量自主抽样时,添加一个索引参数,索引1指截距项,索引2指车重,索引3指发动机排量,如下代码用于绘制车重结果:
> plot(results,index = 2)
为获得车重和发动机排量95%的置信区间,使用以下代码:
> boot.ci(results, type = "bca", index = 2)
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 1000 bootstrap replicates
CALL :
boot.ci(boot.out = results, type = "bca", index = 2)
Intervals :
Level BCa
95% (-5.655, -1.194 )
Calculations and Intervals on Original Scale
> boot.ci(results, type = "bca", index = 3)
BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 1000 bootstrap replicates
CALL :
boot.ci(boot.out = results, type = "bca", index = 3)
Intervals :
Level BCa
95% (-0.0331, 0.0010 )
Calculations and Intervals on Original Scale
在结束自助法前,我们需要关注两个常被提出的有价值的问题:
初始样本需要多大?
应该重复多少次?
对于第一个问题,无法简单回答。有些人认为只要样本能够较好地代表总体,初始样本大小为20~30即可得到足够好的结果。从感兴趣的总体中随机抽样的方法可信度最高,它能够保证初始样本的代表性。对于第二个样本,一般情况下1000次重复在大部分情况下都可满足要求,当然也可以考虑增加重复的次数。