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!