r - 当 R 中的卡方检验生成警告时,如何执行 Fisher 精确检验 `fisher.test()`?

标签 r function statistics compiler-warnings chi-squared

我在 R 中有一个名为 df 的数据框。对于数据框中恰好是一个因素的每个变量,我想执行按受试者性别分层的卡方检验并保存结果 p 值。我已经编写了代码来执行此操作,如下所示。

sapply(df, function(x) if(class(x) == "factor") { chisq.test(table(df$Sex, x))$p.value } )

问题是,当我运行此代码时,我得到以下结果:

There were 50 or more warnings (use warnings() to see the first 50)
warnings()
Warning messages:
1: In chisq.test(table(df$Sex, x)) : Chi-squared approximation may be incorrect

当卡方检验生成警告时,如何修改原始代码以执行 Fisher 精确检验 fisher.test()?我不确定如何让代码识别警告发生时的情况。谢谢!

最佳答案

使用 tryCatch 这些内容可能会有所帮助:

dat = data.frame(x=c(1,0,1,0,1,0,1,1),y=c("A","B","B","A","A","B","A","A"))

#this table is sure to throw a warning
tab = table(dat)
chisq.test(tab)
fisher.test(tab)


#Important part
tryCatch({
  chisq.test(tab)$p.value
}, warning = function(w) {
  fisher.test(tab)$p.value
})

编辑: 如果还希望通过抛出 NA 来绕过错误,则可以修改上面的内容:

tryCatch({
  chisq.test(tab)$p.value
}, warning = function(w) {
  fisher.test(tab)$p.value
}, error = function(e) {
  NA
})

关于r - 当 R 中的卡方检验生成警告时,如何执行 Fisher 精确检验 `fisher.test()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129771/

相关文章:

c++ - 在 C++ 中循环定义函数的参数

algorithm - 有效地找到数组中元素的等级?

python - scipy.stats.chi2_contingency 生成的 p 值用于独立性测试

在标记化之前删除数字、标点符号、空格

r - 每行增加(或不增加)一列的内容

javascript - 我如何从这个函数构造函数中获取全名

function - 旧考试中 Haskell 函数的解释

r - 从汽车包的 Anova 或 Manova 函数的输出中提取多变量测试

r - R 组 Shiny 单选按钮?

r - RMA 随机效应元分析中如何 I^2 ==0(异质性测量)?