## This script provides the methods used to analyze contingency tables ## After opening this file on R (File > Open script ..), select all (by pressing "CTRL + A" and press "CTRL + R" ## The whole script will run in one go if all the required packages are already installed (epiR, psych, DescTools, caret, pwr) # First, generate your contingency table as follows: n4 <- c(40, 30, 60, 70) # Enter the four numbers from your 2x2 table (first column and then second column) ct <- matrix(n4, nrow=2) # By default, byrow = FALSE, so the numbers will be entered into the 2x2 table by column # The 2x2 table is assigned to the name "ct" ct # To check the 2x2 table # Alternative ways of generating a contingency table directly from the data frame (in this case, the "infert" data frame): # ct <- table(infert$induced, infert$case) # This will generate a 3x2 table # Following results can be obtained with base R: fisher.test(ct) chisq.test(ct) # pwr: power analysis # If not installed, install "pwr" # install.packages("pwr") library("pwr") pwr.chisq.test(w = 0.1, N = sum(n4), df = 1, sig.level = 0.05) # w = 0.1 denotes small effect size (see below) pwr.chisq.test(w = 0.3, N = sum(n4), df = 1, sig.level = 0.05) # w = 0.3 denotes medium effect size (see below) pwr.chisq.test(w = 0.5, N = sum(n4), df = 1, sig.level = 0.05) # w = 0.5 denotes large effect size (see below) # w is the effect size, N is the total sample size, and df is the degrees of freedom # Cohen suggests that w values of 0.1, 0.3, and 0.5 represent small, medium, and large effect sizes, respectively # Epidemiologic measures: # If not installed, install "epiR" # install.packages("epiR") # epiR manual @ https://cran.r-project.org/web/packages/epiR/epiR.pdf library("epiR") epi.2by2(ct, method = "cohort.count") # Sensitivity, specificity, PPV/NPV calculation (library: epiR) epi.tests(ct, conf.level = 0.95) # Confusion matrix analysis (see: http://finzi.psych.upenn.edu/R/library/caret/html/confusionMatrix.html & caret.R script) # If not installed, install "caret" # install.packages("caret") library("caret") xtab <- as.table(ct) # converts ct to a class "table" object confusionMatrix(xtab) # Generate a ROC curve: # If not installed, install "psych" # install.packages("psych") library("psych") AUC(ct) # Association measures # FROM: https://www.rdocumentation.org/packages/DescTools/versions/0.99.19/topics/Association%20measures # Package "DescTools": https://www.rdocumentation.org/packages/DescTools/versions/0.99.19/topics/Association%20measures # If not installed, install "DescTools" # install.packages("DescTools") library("DescTools") Phi(ct) ContCoef(ct) CramerV(ct, conf.level = 0.95) TschuprowT(ct) YuleQ(ct) YuleY(ct) Assocs(ct) Desc(ct) # Power of Chi-squared test # SEE: DescTools::power.chisq.test(): https://www.rdocumentation.org/packages/DescTools/versions/0.99.19/topics/power.chisq.test # SEE: https://predictivehacks.com/contingency-tables-in-r (introduces mosaic plots)