Contingency Tables

Harold Nelson

2024-06-04

Setup

# install.packages("gmodels") # Just once
library(gmodels)            # Every Time
load("comics.Rdata")

CrossTable

The method of constructing a contingency table given in the text is cumbersome and doesn’t give a convenient result. It is much better to use the CrossTable() function from the gmodels package. I will show an example based on the comics dataframe, which you can download from Moodle.

Example

CrossTable(comics$align,comics$publisher)
## 
##  
##    Cell Contents
## |-------------------------|
## |                       N |
## | Chi-square contribution |
## |           N / Row Total |
## |           N / Col Total |
## |         N / Table Total |
## |-------------------------|
## 
##  
## Total Observations in Table:  18730 
## 
##  
##                    | comics$publisher 
##       comics$align |        DC |    Marvel | Row Total | 
## -------------------|-----------|-----------|-----------|
##                Bad |      2724 |      6352 |      9076 | 
##                    |    10.136 |     4.748 |           | 
##                    |     0.300 |     0.700 |     0.485 | 
##                    |     0.456 |     0.498 |           | 
##                    |     0.145 |     0.339 |           | 
## -------------------|-----------|-----------|-----------|
##               Good |      2697 |      4310 |      7007 | 
##                    |    95.372 |    44.677 |           | 
##                    |     0.385 |     0.615 |     0.374 | 
##                    |     0.451 |     0.338 |           | 
##                    |     0.144 |     0.230 |           | 
## -------------------|-----------|-----------|-----------|
##            Neutral |       551 |      2093 |      2644 | 
##                    |   101.404 |    47.502 |           | 
##                    |     0.208 |     0.792 |     0.141 | 
##                    |     0.092 |     0.164 |           | 
##                    |     0.029 |     0.112 |           | 
## -------------------|-----------|-----------|-----------|
## Reformed Criminals |         3 |         0 |         3 | 
##                    |     4.361 |     2.043 |           | 
##                    |     1.000 |     0.000 |     0.000 | 
##                    |     0.001 |     0.000 |           | 
##                    |     0.000 |     0.000 |           | 
## -------------------|-----------|-----------|-----------|
##       Column Total |      5975 |     12755 |     18730 | 
##                    |     0.319 |     0.681 |           | 
## -------------------|-----------|-----------|-----------|
## 
##