How to find the count of each category in an R data frame column?


To find the count of each category in an R data frame column, we can follow the below steps −

  • First of all, create a data frame.

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

Example

Create the data frame

Let’s create a data frame as shown below −

Grp<-sample(LETTERS[1:5],25,replace=TRUE)
DV<-rpois(25,10)
df<-data.frame(Grp,DV)
df

Output

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

  Grp DV
1  D  15
2  C   8
3  B   8
4  A  10
5  D   7
6  D  16
7  B  12
8  A   7
9  E   9
10 B  15
11 C  14
12 E   4
13 C  10
14 B  12
15 C  10
16 C  12
17 E  11
18 E  10
19 C  10
20 D  11
21 D   4
22 C   7
23 D  10
24 C  11
25 E   8

Find the count of each category in data frame

Using summarise function of dplyr package after grouping along with n to find the count of each category in Grp column of data frame df −

Grp<-sample(LETTERS[1:5],25,replace=TRUE)
DV<-rpois(25,10)
df<-data.frame(Grp,DV)
library(dplyr)
df %>% group_by(Grp) %>% summarise(count=n())

Output

# A tibble: 5 x 2
Grp count
 <chr> <int>
1 A     4
2 B     3
3 C     8
4 D     5
5 E     5

Updated on: 16-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements