如何在R中用boot()函数对male.wt数据集执行Bootstrap抽样并估计方差?
Bootstrap抽样估计男性出租车乘客体重的总体方差
以下是使用R语言boot包完成Bootstrap抽样估计的完整步骤:
1. 安装并加载boot包
如果还未安装boot包,先执行安装命令:
install.packages("boot")
加载包:
library(boot)
2. 导入数据集
将你提供的数据集加载到R中:
malewt = structure(list(x = c(184.291514203183, 238.183299307855, 217.544606414151, 233.931926116624, 229.12042611005, 243.881689583996, 259.230802242781, 217.939619221934, 137.636923032685, 170.379447345948, 195.852641733122, 185.832690963969, 186.676714564328, 215.711426139253, 186.413495533494, 237.83223009147, 180.124153998503, 215.393108191779, 188.846039074142, 142.373198101437, 233.234630310378, 186.141325709762, 220.062112044187, 213.851199681057, 148.622198219149, 197.438771523918, 206.920961557603, 190.874857845699, 217.889075914836, 152.318099234166, 218.089620221194, 196.736930479919, 235.122424359223, 217.446826955801, 201.352404389309, 216.290374765672, 173.85609629461, 215.961826427613, 213.87732008193, 177.952521505061, 132.734879010504, 221.707886490889, 224.336488758995, 218.604034088911, 228.157844234374, 196.544661577149, 228.787736646279, 237.009125179319, 194.73342863066, 190.569523115323, 192.198491573128, 204.589742888237, 198.662802876867, 195.238634847898, 201.834508205684, 220.989134791548, 180.006492709174, 168.199898332071, 250.705048451896, 209.824701073225, 212.36145906497, 205.250728119598, 196.572466206237, 186.818746613236, 138.493748904934, 193.572713536688, 171.605082170236, 243.803356964054, 188.768040728907, 201.408088256783, 196.23847341016, 202.686141019735, 167.25735383257, 171.907526464761, 224.396425425799, 183.494470842407, 220.15969728649, 143.164453849305, 152.539942653094, 198.52004650272, 185.145815429412, 206.741840856439, 259.866591064748, 135.212011256414, 164.2297511973, 200.623731663392, 199.599177980586, 175.970651370212, 197.304554981825, 189.116019204125, 198.630618004183, 185.096675814379, 203.780160863916, 174.584831373708, 150.483001599829, 223.78078870159, 170.772181294322, 218.770812392057, 151.645084212409, 210.350813872005)), class = "data.frame", row.names = c(NA, -100L ))
3. 定义Bootstrap统计函数
编写一个函数,输入原始数据和抽样索引,返回该样本的方差:
var_bootstrap <- function(data, indices) { # 从原始数据中按索引抽取Bootstrap样本 sample_data <- data$x[indices] # 计算样本方差 var(sample_data) }
4. 执行Bootstrap抽样
调用boot()函数,指定数据集、统计函数和抽样次数(这里用10000次,次数越多结果越稳定):
boot_result <- boot(data = malewt, statistic = var_bootstrap, R = 10000)
5. 查看结果
打印Bootstrap结果:
print(boot_result)
输出包含:
t0:原始样本的方差t:10000次Bootstrap样本的方差集合- 标准差估计等信息
获取Bootstrap估计值和置信区间
计算所有Bootstrap样本方差的均值,作为总体方差的Bootstrap估计:
mean(boot_result$t)
生成95%置信区间:
boot.ci(boot_result, type = c("norm", "basic", "perc"))
这里提供三种常见的置信区间类型:正态近似、基础Bootstrap、百分位数法,可按需选择。
结果解释
- Bootstrap估计值:多次抽样得到的方差平均值,是总体方差的无偏估计
- 置信区间:表示我们有95%的把握认为总体方差落在该区间内
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

