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

如何在循环遍历列表时输出变量名并执行卡方检验

解决方法

你的问题核心是dataList只存储了变量的取值,没保留变量名称,导致循环时无法获取变量名。直接遍历变量名字符向量就能解决这个问题,既能拿到变量名,又能提取对应数据做检验。

修改后的代码

1. 定义变量名字符向量

不用把变量值存入列表,直接把要检验的变量名写成字符向量:

# 定义待检验的变量名向量
var_names <- c(
  "Immigrant", "Known to Police or FBI", "Criminal Record",
  "History of Physical Altercations", "History of Animal Abuse",
  "History of Domestic Abuse", "History of Sexual Offenses", "Gang Affiliation",
  "Terror Group Affiliation", "Bully", "Bullied", "Raised by Single Parent",
  "Parental Divorce / Separation", "Parental Death in Childhood",
  "Parental Suicide", "Childhood Trauma", "Physically Abused",
  "Sexually Abused", "Emotionally Abused", "Neglected",
  "Mother Violent Treatment", "Parental Substance Abuse",
  "Parent Criminal Record", "Family Member Incarcerated",
  "Signs of Being in Crisis", "Inability to Perform Daily Tasks",
  "Notably Depressed Mood", "Unusually Calm or Happy", "Rapid Mood Swings",
  "Increased Agitation", "Abusive Behavior", "Isolation",
  "Losing Touch with Reality", "Paranoia", "Prior Hospitalization",
  "Prior Counseling", "Psychiatric Medication", "Treatment 6 Months Prior to Shooting",
  "Autism Spectrum", "Health Issues", "Head Injury / Possible TBI",
  "Motive: Racism/Xenophobia", "Motive: Religious Hate", "Motive: Misogyny",
  "Motive: Homophobia", "Motive: Employment Issue",
  "Motive: Economic Issue", "Motive: Legal Issue", "Motive: Relationship Issue",
  "Motive: Fame-Seeking", "Motive: Unknown", "Role of Psychosis in the Shooting",
  "Interest in Past Mass Violence", "Relationship with Other Shooting(s)",
  "Planning", "Performance", "Interest in Firearms"
)

2. 遍历变量名执行卡方检验

循环时直接用变量名,通过db.binom[[var]]提取变量值,同时打印变量名:

# 循环执行卡方检验并输出变量名
for(var in var_names){
  # 打印当前检验的变量名
  cat("当前检验变量:", var, "\n\n")
  # 构建公式并执行检验
  test_result <- chisq.bintest(
    formula = as.factor(shooter) ~ .data[[var]], 
    data = db.binom, 
    correct = FALSE, 
    alpha = 0.05, 
    p.method = "fdr"
  )
  # 打印检验结果
  print(test_result)
  cat("-----------------------------------------\n\n")
}

关键说明

  • 使用.data[[var]]是规范的引用方式,能确保公式正确识别字符类型的变量名,避免语法错误。
  • 用cat打印变量名比print更清晰,方便区分不同变量的检验结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:45:30