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

 Live Demo

Consider the below data frame −

x1<−sample(c("Child","Teen","Adult","Old"),20,replace=TRUE)
x2<−sample(c("Unemployed","Employed"),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1

Output

x1 x2
1 Old Unemployed
2 Child Unemployed
3 Adult Employed
4 Adult Unemployed
5 Adult Employed
6 Teen Employed
7 Old Employed
8 Child Unemployed
9 Child Employed
10 Adult Unemployed
11 Child Unemployed
12 Old Employed
13 Child Unemployed
14 Child Employed
15 Teen Employed
16 Adult Employed
17 Adult Unemployed
18 Old Employed
19 Adult Unemployed
20 Child Employed

Finding the counts of categories in both columns of df1 −

Example

table(df1$x1,df1$x2)

Output

Employed Unemployed
Adult 3 4
Child 3 4
Old 3 1
Teen 2 0

Example2

 Live Demo

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: 09-Feb-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements