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

批量执行Wilcoxon秩和检验报错求助:att变量与country分组

批量执行Wilcoxon秩和检验的修正方案

问题分析

你的代码存在几个核心问题:

  • 数据集命名不统一:定义的数据集是wil,但循环里误用了bank
  • 循环逻辑错误:for(i in bank)会遍历数据框的列值而非列索引/列名,导致公式构建失败
  • 未正确筛选目标变量:没有用grep匹配att前缀的变量
  • 结果列表初始化错误:modellist<-list(bank)不符合需求

修正后的代码

# 加载示例数据集(统一用wil作为数据集名)
wil<-structure(list(country = c("Colombia-Bucaramanga", "Colombia-Bucaramanga", 
"Colombia-Bucaramanga", "Colombia-Bucaramanga", "Colombia-Bucaramanga"), Fecha_bankssp = c(44422L, 44423L, 44423L, 44423L, 44423L), att1_goodofall = structure(c(4L, 4L, 2L, 4L, 4L), label = "Good of all", class = c("labelled", "integer")), att2_pvtdisease = structure(c(4L, 4L, 3L, 3L, 4L), label = "Helps prevent disease", class = c("labelled", "integer")), att3_curedisease = structure(c(4L, 2L, 4L, 3L, 3L), label = "Helps cure disease", class = c("labelled", "integer")), att4_timewaste = structure(c(4L, 4L, 3L, 5L, 4L), label = "Waste of time", class = c("labelled", "integer")), att5_helpgenerations = structure(c(4L, 4L, 4L, 4L, 3L), label = "Benefits future generations", class = c("labelled","integer")), att6_healthinterfere = structure(c(4L, 3L, 3L, 5L, 3L), label = "Interferes with health", class = c("labelled", "integer")), att7_helpfamily = structure(c(4L, 3L, 3L, 3L, 4L), label = "Helps family", class = c("labelled", "integer")), att8_noriskstolen = structure(c(4L, 2L, 3L, 4L, 2L), label = "Medical information is not stolen", class = c("labelled", "integer")), att9_helpdengue = structure(c(4L, 4L, 4L, 4L, 2L), label = "Advances dengue research", class = c("labelled", "integer")), att10_perinfosafe = structure(c(4L, 4L, 3L, 4L, 2L), label = "Personal information is safe", class = c("labelled", "integer")), att11_identhealthproblem = structure(c(4L, 2L, 3L, 3L, 4L), label = "Helps to identify health problem", class = c("labelled", "integer")), att12_highmedicalcost = structure(c(4L, 3L, 2L, 4L, 3L), label = "Further increases medical costs", class = c("labelled", "integer"))), row.names = c(NA, 5L), class = "data.frame")

# 筛选所有以att开头的变量
att_vars <- grep("^att", names(wil), value = TRUE)

# 初始化结果列表
model_list <- list()

# 循环执行Wilcoxon秩和检验
for(var in att_vars) {
  # 构建正确的公式:变量 ~ country
  fmla <- as.formula(paste(var, "~ country"))
  # 执行检验(示例数据中country只有一个分组,实际运行会有警告)
  model_list[[var]] <- wilcox.test(fmla, data = wil, paired = FALSE)
}

# 查看单个变量的检验结果示例
model_list[["att1_goodofall"]]

关键说明

  1. 变量筛选:grep("^att", names(wil), value = TRUE)用正则表达式^att精准匹配以att开头的列名,解决你之前无法匹配的问题
  2. 循环逻辑:直接遍历筛选后的变量名列表,避免索引混乱
  3. 公式构建:用paste(var, "~ country")生成正确的公式字符串,再转为公式对象
  4. 注意事项:你的示例数据中country只有一个取值,实际运行会抛出分组不足的警告,需确保真实数据中country至少有两个分组

内容的提问来源于stack exchange,提问作者Mahir Bhatt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:10:33