How to create frequency table of data.table in R?

R ProgrammingServer Side ProgrammingProgramming

If we have an data.table object or a data frame converted to a data.table and it has a factor column then we might want to create a frequency table that shows the number of values each factor has or the count of factor levels. This is a data summarization method which helps us to understand the variation in the occurrences of factor levels. This can be easily done with a single line of code if we have a data.table object, otherwise we first need to convert the object.

Example

Consider the below data frame −

 Live Demo

Group<-sample(c("A","B","C","D"),20,replace=TRUE)
Frequency<-sample(1:50,20)
df1<-data.frame(Group,Frequency)
df1

Output

 Group Frequency
1   A    11
2   B    19
3   A    41
4   D    24
5   A    22
6   B    26
7   C    46
8   C    4
9   A    45
10  C    44
11  A    50
12  C    20
13  B    27
14  D    12
15  A    34
16  B    6
17  C    35
18  D    32
19  A    42
20  D    30

Loading data.table package and reading the data frame df1 as data.table −

Example

library(data.table)
df1<-as.data.table(df1)

Finding the frequency table of df1 which is a data.table object now −

Example

df1[,.N,by=Group]

Output

 Group N
1: A   7
2: B   4
3: D   4
4: C   5

Let’s have a look at another example −

Example

 Live Demo

Class<-sample(c("1","2","3","4","5"),20,replace=TRUE)
Scores<-sample(1:100,20)
df2<-data.frame(Class,Scores)
df2

Output

 Class Scores
1  2    45
2  5    66
3  4    61
4  5    96
5  3    27
6  5    94
7  5    51
8  3    98
9  1    14
10 3    83
11 3    6
12 1    16
13 1    18
14 1    35
15 2    70
16 4    67
17 1    63
18 5    31
19 1    58
20 4    15

Example

df2<-as.data.table(df2)
df2[,.N,by=Class]

Output

 Class N
1: 2   2
2: 5   5
3: 4   3
4: 3   4
5: 1   6
raja
Published on 08-Sep-2020 12:53:46
Advertisements