How to find the frequency table for factor columns in an R data frame?


If we have factor columns in an R data frame then we want to find the frequency of each factor level for all the factor columns. This can be done with the help of sapply function with table function. For example, if we have a data frame called df that contains some factor columns then the frequency table for factor columns can be created by using the command sapply(df,table).

Example1

Consider the below data frame −

Live Demo

> x1<-sample(LETTERS[1:4],20,replace=TRUE)
> x2<-sample(letters[1:4],20,replace=TRUE)
> df1<-data.frame(x1,x2)
> df1

Output

   x1 x2
1  D  a
2  D  b
3  D  c
4  D  b
5  D  c
6  C  a
7  C  a
8  B  a
9  A  a
10 C  c
11 D  a
12 D  b
13 D  b
14 A  c
15 C  b
16 D  a
17 A  b
18 A  b
19 B  c
20 C  b

Finding the frequency table for factor columns in df1 −

> sapply(df1,table)
$x1

Output

A B C D
4 2 5 9

Example

$x2

Output

a b c
7 8 5

Example2

Live Demo

> y1<-sample(c("India","Russia","UK"),20,replace=TRUE)
> y2<-sample(c("Male","Female"),20,replace=TRUE)
> df2<-data.frame(y1,y2)
> df2

Output

    y1      y2
1  India    Male
2  UK     Female
3  Russia   Male
4  India  Female
5  India  Female
6  India    Male
7  UK     Female
8  Russia   Male
9  UK       Male
10 India    Male
11 Russia   Male
12 UK       Male
13 UK     Female
14 India  Female
15 India  Female
16 Russia Female
17 Russia Female
18 Russia Female
19 India  Female
20 India  Female

Finding the frequency table for factor columns in df2 −

> sapply(df2,table)
$y1

Output

India Russia UK
  9     6    5

Example

$y2

Output

Female Male
  12    8

Updated on: 05-Mar-2021

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements