#' --- #' title: Two way tables #' author: Carolyn J. Anderson #' date: May 2018 #' --- # Modification of Friendly & Meyer 2-way R tutorial # http://euclid.psych.yorku.ca/www/psy6136/tutorials/twoway.pdf # # Packages needed: # vcd # MASS # library(vcd) data("Hospital",package="vcd") Hospital # 1. Find marginal frequencies margin.table(Hospital,1) # row margins frequencies margin.table(Hospital,2) # column margins frequencies # 2. Add marginal frequencies to table addmargins(Hospital) # 3. Find marginal proportions prop.table(Hospital,1) # row marginal proportions prop.table(Hospital,2) # column marginal proportions # 4. Perform Pearson chi-square test (asympotic) chisq.test(Hospital) # 5. Perform Monte Carlo chi-square test (non-asympotic) chisq.test(Hospital, simulate.p.value=TRUE) # For more information about the simulated tests, ?chisq.test # 6. Use loglm (log-linear model) to do chi-square test library(MASS) ( model.loglm <- loglm(~ 1 + 2, Hospital) ) # 7. Use glm (generalized linear model) to test association (this will be used for many models) # a. Turn table into data.frame ( hospital <- as.data.frame(Hospital) ) # b. Use glm, model.glm <- glm(Freq ~ Visit.frequency + Length.of.stay, data=hospital,family=poisson) summary(model.glm) # c. The "Residual Deviance" is the likelihood-ratio goodness-of-fit statistic. # Compare this to value given by loglm # 8. Compute association statistics assocstats(Hospital) ############### Figures Showing association in table ################## # A nice web-site for colors: # http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf # and for palettes # https://www.r-bloggers.com/palettes-in-r/ # # par=(mfrow=c(2,2)) # 9. Bar chart bar.colors <- c("red","blue","green") # I defined pallette par(cex=1.2) barplot(Hospital, beside=TRUE, legend=TRUE,col=bar.colors, main="Hospital Data from vcd Package", xlab="Length of Stay in Days", ylab="Frequency", ) # 10. Tile plot tile(Hospital) # 11. Plot plot(Hospital,col="cornflowerblue") # 12. Spine plot spineplot(Hospital,col="cornflowerblue") box.colors=rainbow(6, s=0.6) # pre-defined palette spineplot(Hospital,col=box.colors) # 13. Mosaic mosaic(Hospital)