#Mcnamar test for 2 related populations library(dplyr) library(ggplot2) library(reshape2) library(DescTools) # Table entries a <- 20 b <- 5 c <- 7 d <- 3 #create contingency table ba_tab = as.table(matrix( c(20, 7, 5, 3), ncol=2, dimnames = list(c("Satisfactory","Unsatisfactory"), c("Satisfactory","Unsatisfactory")))) ba_tab #set up data to generate bar charts ba_tab_m <- melt(ba_tab, varnames = c("Before", "After"), id.vars = "After") #set up data frame to generate bar charts ggplot(ba_tab_m %>% group_by(Before) %>% mutate(Percentage = round(value/sum(value),2)), aes(x=Before, y = Percentage, fill = After, cumulative = TRUE)) + geom_col() + geom_text(aes(label = paste0(Percentage*100,"%")), position = position_stack(vjust = 0.5)) #column percentages PercTable(ba_tab, row.vars = NULL, col.vars = NULL, justify = "right", freq = TRUE, rfrq = "001", expected = FALSE, residuals = FALSE, stdres = FALSE, margins = c(1,2), digits = 0) #row percentages PercTable(ba_tab, row.vars = NULL, col.vars = NULL, justify = "right", freq = TRUE, rfrq = "010", expected = FALSE, residuals = FALSE, stdres = FALSE, margins = c(1,2), digits = 0) #Mcnamar Test mcnemar.test(ba_tab,correct = FALSE) #Since b+c < 25, we will use the exact test #To use the binomial test we use b as the number of successes and # n=b+c as the sample size binom.test(x=5, n=12 , p = 0.5)