Contigency R
Contigency R
A,B,C(AIDS) Date:
Contingency Table:
A contingency table (also known as a cross-tabulation or crosstab) is a table used to display the frequency
distribution of two or more categorical variables. In R, you can create a contingency table from vectors using
the table() function.
1. Creating a Contingency Table from Vectors
Suppose you have two categorical vectors (e.g., gender and favorite color). You can create a contingency table
to see the frequency distribution of these two variables.
Example:
Output:
favorite_color
gender Blue Green Red
Female 1 0 3
Male 2 2 0
In this example:
You can add row and column totals (margins) to the table using the addmargins() function.
Session 2024-25
Output:
favorite_color
gender Blue Green Red Sum
Female 1 0 3 4
Male 2 2 0 4
Sum 3 2 3 8
3. Proportions in Contingency Table
a) Cell Proportions
Output:
favorite_color
gender Blue Green Red
Female 0.125 0.000 0.375
Male 0.250 0.250 0.000
To get the proportions within each row (e.g., within each gender group):
# Proportions by row
prop_table_row <- prop.table(contingency_table, margin = 1)
print(prop_table_row)
Output:
favorite_color
gender Blue Green Red
Female 0.25 0.00 0.75
Male 0.50 0.50 0.00
This tells you the proportion of each favorite color within the Female and Male categories.
c) Column-wise Proportions
Similarly, to get proportions within each column (e.g., within each favorite color group):
# Proportions by column
prop_table_col <- prop.table(contingency_table, margin = 2)
print(prop_table_col)
Output:
favorite_color
gender Blue Green Red
Female 0.333 0.000 1.000
Male 0.667 1.000 0.000
Session 2024-25
This gives you the proportion of each gender within each color category.
You can also create contingency tables from data frames. If the variables are columns in a data frame, use the
table() function directly on those columns.
Example:
You can visualize contingency tables using bar plots or mosaic plots in R.
a) Bar Plot
b) Mosaic Plot
Session 2024-25
Session 2024-25
Session 2024-25
Session 2024-25
Session 2024-25