R语言survey包报错Error in xx[[1]] : subscript out of bounds求助
解决survey包中
Error in xx[[1]] : subscript out of bounds错误 错误原因
你遇到的错误是因为分层抽样设计中单个层内的PSU设置不符合survey包的计算要求:
- 测试数据里所有样本都属于同一个stratum(值为1),但你使用了
strata = ~stratum声明分层抽样。 - survey包计算抽样方差时,要求每个分层至少包含2个独立的PSU,否则会触发下标越界的计算错误。
解决方法
根据你的数据情况,有两种可行的修正方案:
方案1:移除分层参数(适用于无分层的抽样设计)
如果你的实际抽样并没有分层(测试数据中stratum全为1也说明这一点),直接去掉strata参数或设置为NULL:
library(survey) df <- data.frame( pid = 1:10, sex = rep(c('Men', 'Women'), each = 5), stratum = rep(1, 10), psu = c('101007', '201139', '202002', '101007', '201139', '202002', '101007', '201139', '202002', '101007'), wstep1 = c(2644.070, 5990.753, 2909.657, 2909.657, 3305.544, 6980.915, 2909.657, 4719.190, 2909.657, 3393.434) ) # 移除strata参数,或设置strata = NULL test_weigh <- svydesign(ids = ~psu, weights = ~wstep1, data = df ) # 计算加权总人数 total_individuals_alg <- svytotal(~1, design = test_weigh, na.rm = TRUE) # 查看结果 total_individuals_alg
运行后会得到正确的加权总人数及标准误:
total SE 1 38772.93 1312.82
方案2:修正分层变量(适用于实际存在分层的场景)
如果你的实际数据确实是分层抽样,需要确保每个stratum下至少有2个不同的PSU。比如修改测试数据的stratum变量,分成两个层:
df$stratum <- rep(c(1,2), each=5) test_weigh <- svydesign(ids = ~psu, weights = ~wstep1, strata = ~stratum, data = df ) total_individuals_alg <- svytotal(~1, design = test_weigh, na.rm = TRUE) total_individuals_alg
这样也能正常运行,得到正确结果。
内容的提问来源于stack exchange,提问作者yyyyyycccc
相关产品推荐
相关产品推荐

