You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用survey包svyby结合svyquantiles计算子群体中位数报错求助

问题描述

我正在阅读《Complex Survey》一书,尝试复现书中代码,但因书籍版本较旧,代码无法正常运行。我想要使用survey包的svyby函数计算子群体的中位数,使用的数据集为Adult.dta。

首先加载survey和haven包,读取数据后需要执行chis_adult <- as.data.frame(chis_adult)才能成功创建svrepdesign设计对象:

library(survey)
library(haven)
chis_adult <- read_dta("Adult.dta")
chis_adult <- as.data.frame(chis_adult)
chis <- svrepdesign(variables = chis_adult[,1:418],
                    repweights = chis_adult[,420:499],
                    weights = chis_adult[,419], combined.weights = T,
                    type= "other", scale = 1, rscales =1)

随后运行以下代码计算srsex+racehpr分组下bmi_p的中位数:

medians <- svyby(~bmi_p, ~srsex+racehpr, svyquantile, design = chis, 
                 quantiles = 0.5, covmat = T)

出现错误:

Error in (function (cond)  : 
  error in evaluating the argument 'x' in selecting a method for function 't': Can't merge the outer name `ci` with a vector of length > 1.
Please supply a `.name_spec` specification.

我尝试设置na.rm = T, na.rm.by = T, na.rm.all = T等参数均无效,请问问题出在哪里?

问题原因与解决方法

问题出在svyquantile结合covmat=TRUE时的结果结构上:svyquantile会返回包含分位数估计值、置信区间(ci,长度为2)以及协方差矩阵的复合结果,而svyby默认的命名规则无法处理这类嵌套的多元素结果,导致命名冲突。

解决方法是给svyby添加.name_spec参数,明确结果列的命名规则,避免冲突。比如使用{outer}_{inner}格式,让外层分组与内层统计量组合成唯一列名:

medians <- svyby(~bmi_p, ~srsex+racehpr, svyquantile, design = chis, 
                 quantiles = 0.5, covmat = TRUE,
                 .name_spec = "{outer}_{inner}")

如果不需要协方差矩阵,也可以直接去掉covmat=TRUE参数,此时svyquantile仅返回分位数估计值和置信区间,默认命名规则即可正常处理:

medians <- svyby(~bmi_p, ~srsex+racehpr, svyquantile, design = chis, 
                 quantiles = 0.5)

内容的提问来源于stack exchange,提问作者Victor Shin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 08:32:16