通常,在引导之后,我们使用 2.5% 和 97.5% 百分位数作为 95% 置信区间(因为我们从每一边减去 α/2=.025)。也可以看看@索塔尔的 answer以及答案下的评论。
R <- 1e5 - 1 ## number of bootstrap replications
est <- with(law, cor(lsat, gpa)) ## naïve correlation
theta <- function(ind) cor(law[ind, 1], law[ind, 2], method="pearson")
set.seed(1)
B1 <- bootstrap::bootstrap(seq(nrow(law)), R, theta)
(ci1 <- c(estimate=est, quantile(B1$thetastar, c(.025, .975))))
# estimate 2.5% 97.5%
# 0.7763745 0.4594845 0.9620884
这是从头开始的替代方法:
theta2 <- function(x) with(x, cor(lsat, gpa))
set.seed(1)
B2 <- replicate(R, theta2(law[sample(nrow(law), nrow(law), replace=TRUE), ]))
(ci2 <- c(estimate=est, quantile(B2, c(.025, .975))))
# estimate 2.5% 97.5%
# 0.7763745 0.4607644 0.9617970
最后一种方法是使用boot
包中有一个boot.ci
功能:
theta3 <- function(data, k) cor(data[k, ])[1,2]
set.seed(1)
B3 <- boot::boot(law, theta3, R=R)
(ci3 <- c(est, boot::boot.ci(B3, type='perc')$percent[4:5]))
# [1] 0.7763745 0.4593727 0.9620923