2
votes

I have a data frame in R named 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. 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? I'm not sure how to get the code to recognize when a warning occurs. Thanks!

1
use fishers all the time?rawr

1 Answers

3
votes

Using tryCatch something along these lines might help:

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:

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