The table()
function from R base
creates frequency tables that summarize categorical data. We can also use function xtab
from R stats
package.
In our data we want to make a cross tabulate or contingency table for variables ses and honors.
#Tow-way Contingency Table
tab1 <- table(hsb$ses, hsb$honors)
tab1
##
## enrolled not enrolled
## high 26 32
## low 11 36
## middle 16 79
#Proportional table
prop.table(tab1)
##
## enrolled not enrolled
## high 0.130 0.160
## low 0.055 0.180
## middle 0.080 0.395
#Proportional table by row
prop.table(tab1, margin = 1)
##
## enrolled not enrolled
## high 0.4482759 0.5517241
## low 0.2340426 0.7659574
## middle 0.1684211 0.8315789
#Tow-way Contingency Table
tab2 <- xtabs(~ ses + honors, data = hsb)
tab2
## honors
## ses enrolled not enrolled
## high 26 32
## low 11 36
## middle 16 79
#Proportional table
prop.table(tab2)
## honors
## ses enrolled not enrolled
## high 0.130 0.160
## low 0.055 0.180
## middle 0.080 0.395
#Proportional table by row
prop.table(tab2, margin = 1)
## honors
## ses enrolled not enrolled
## high 0.4482759 0.5517241
## low 0.2340426 0.7659574
## middle 0.1684211 0.8315789
#Summary on a table object will perform a chi-squared test
summary(tab2)
## Call: xtabs(formula = ~ses + honors, data = hsb)
## Number of cases in table: 200
## Number of factors: 2
## Test for independence of all factors:
## Chisq = 14.783, df = 2, p-value = 0.0006164
#Three-way cross tab
tab3 <- xtabs(~ ses + honors + female, data = hsb)
tab3
## , , female = female
##
## honors
## ses enrolled not enrolled
## high 15 14
## low 10 22
## middle 10 38
##
## , , female = male
##
## honors
## ses enrolled not enrolled
## high 11 18
## low 1 14
## middle 6 41
ftable(tab3)
## female female male
## ses honors
## high enrolled 15 11
## not enrolled 14 18
## low enrolled 10 1
## not enrolled 22 14
## middle enrolled 10 6
## not enrolled 38 41