【问题标题】:How to perform a Fisher's exact test `fisher.test()` when a warning is generated by the Chi square test in R?当R中的卡方检验生成警告时,如何执行Fisher精确检验`fisher.test()`?
【发布时间】:2015-05-21 16:37:20
【问题描述】:

我在 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()?我不确定如何让代码在出现警告时进行识别。谢谢!

【问题讨论】:

  • 一直使用渔夫?

标签: r function statistics compiler-warnings chi-squared


【解决方案1】:

使用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
})

【讨论】:

  • 这段代码看起来很棒。现在我遇到了一个不同的问题...Error in fisher.test(table(df$Sex, x)) : FEXACT error 40. Out of workspace. 我想是因为我的数据的性质?有没有办法忽略这一点,只需将NA 作为这些变量的 p 值?
  • 也许添加一些工作区(默认为 200000)fisher.test(table(df$Sex, x),workspace=1000000) 可以解决问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-11
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2016-04-29
  • 2021-05-18
相关资源
最近更新 更多