简体   繁体   English

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

[英]How to perform a Fisher's exact test `fisher.test()` when a warning is generated by the Chi square test in R?

I have a data frame in R named df . 我在R中有一个名为df的数据框。 For every variable in the data frame that happens to be a factor, I want to perform a Chi square test stratified by the subject's gender and save the resulting p value. 对于数据帧中恰好是一个因素的每个变量,我要执行按受试者性别分层的卡方检验,并保存结果p值。 I have written code to do this, shown below. 我已经编写了代码来做到这一点,如下所示。

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

The problem is, when I run this code, I get the following: 问题是,当我运行此代码时,得到以下信息:

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

How can I modify my original code to instead perform a Fisher's exact test fisher.test() when a warning is generated by the Chi square test? 当卡方检验生成警告时,如何修改原始代码以执行Fisher精确检验fisher.test() I'm not sure how to get the code to recognize when a warning occurs. 我不确定如何在发生警告时识别代码。 Thanks! 谢谢!

Using tryCatch something along these lines might help: 按照以下方式使用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
})

Edit: If one also wishes to bypass errors by throwing NA the above might be modified: 编辑:如果还希望通过抛出NA来绕过错误,则可以修改以上内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM