How to find the count of each category in a data.table object column in R?

R ProgrammingServer Side ProgrammingProgramming

To find the count of each category in a data.table object column in R, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use summarise function of dplyr package after grouping along with n.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
factor<-sample(c("very low","low","medium","high","very high"),25,replace=TRUE)
response<-rnorm(25)
DT<-data.table(factor,response)
DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    factor        response
1:  very high  -0.14064701
2:   high      -0.36029663
3:   low       -0.50825291
4:  very high  -2.07959316
5:  high        0.25578922
6:  very high   1.17946264
7:  low         1.32803179
8:  medium     -0.23736325
9:  medium     -0.07440274
10: very low    0.32669673
11: very low    0.54953485
12: high       -0.93197732
13: very high  -0.77787846
14: very low    0.63808636
15: very high   0.76008767
16: very high  -0.38712279
17: very high  -0.64259955
18: high        0.30249791
19: high        0.16984229
20: very low   -0.24732679
21: high       -0.47456705
22: low         0.08789350
23: low         0.32541943
24: medium     -0.27170782
25: high       -0.09860207
   factor        response

Find the count of each category in data.table object

Using summarise function of dplyr package after grouping along with n to find the count of each category in factor column of data.table object DT −

library(data.table)
factor<-sample(c("very low","low","medium","high","very high"),25,replace=TRUE)
response<-rnorm(25)
DT<-data.table(factor,response)
library(dplyr)
DT %>% group_by(factor) %>% summarise(count=n())

Output

# A tibble: 5 x 2
  factor   count
  <chr>    <int>
1 high       7
2 low        4
3 medium     3
4 very high  7
5 very low   4
raja
Published on 09-Nov-2021 06:46:59
Advertisements