Creating and Summarizing Contingency Tables in R
Hi, Welcome Back!
In R, contingency tables are essential for analyzing relationships between categorical data. This tutorial covers how to generate and interpret one-way, two-way, and multi-dimensional tables using R's built-in functions.
1. Generate (1) a one-way table for "purchased" and (2) a two-way table for "country" and "purchased.
- One-way table for "purchased": The table(df$purchased)
line generates a one-way table for the "purchased" column, counting occurrences of "Yes" and "No".
- Two-way table for "country" and "purchased": The table(df$country, df$purchased)
line creates a two-way table that cross-tabulates "country" and "purchased," showing how many records have each combination of country and purchase status.
INPUT:
OUTPUT:
2. Generate contingency table also known as rx C table using mtcars dataset.
- Contingency Table (r x C Table):
mtcars_df
is created to show the counts of each combination of gears and cylinders.- Adding Row and Column Totals:
addmargins(mtcars_df)
adds the row and column totals to this table.- Proportional Weights:
prop.table(mtcars_df)
calculates the proportion of each count relative to the total number of cars.INPUT:
Comments
Post a Comment