How to find the counts of categories in categorical columns in an R data frame?

If we have two categorical columns in an R data frame then we can find the frequency/count of each category with respect to each category in the other column. This will help us to compare the frequencies for all categories. To find the counts of categories, we can use table function as shown in the below examples.

Example1

y1<−sample(c("Married","Unmarried"),20,replace=TRUE)
y2<−sample(c("Satisfied","Not-Satisfied"),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2

Output

y1 y2
1 Married Not-Satisfied
2 Unmarried Not-Satisfied
3 Married Not-Satisfied
4 Unmarried Not-Satisfied
5 Married Satisfied
6 Married Not-Satisfied
7 Unmarried Satisfied
8 Married Satisfied
9 Unmarried Not-Satisfied
10 Unmarried Not-Satisfied
11 Unmarried Not-Satisfied
12 Unmarried Not-Satisfied
13 Married Satisfied
14 Married Satisfied
15 Married Satisfied
16 Married Not-Satisfied
17 Married Satisfied
18 Unmarried Satisfied
19 Married Satisfied
20 Married Satisfied

Finding the counts of categories in both columns of df2 −

Example

table(df2$y1,df2$y2)

Output

Not−Satisfied Satisfied
Married 4 8
Unmarried 6 2
Updated on: 2026-03-11T22:50:55+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements