Open In App

How to Create Frequency Table by Group using Dplyr in R

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be looking at the approach to creating a frequency table group with its working examples in the R programming language.

Create Frequency Table by Group using dplyr package:

In this approach to create the frequency table by group, the user first needs to import and install the dplyr package in the working console, and then the user needs to call the group_by() and the summarize() function from the dplyr() package, here the group_by() function is responsible for to make groups of the data frames. Group_by() function alone doesn’t give any output so it should be followed by summarise() function with an appropriate action to perform. This works similar to GROUP BY used in SQL and pivot table in excel.

Syntax to install and import the dplyr package in the R console:

install.package('dplyr')
library(dplyr)

Example 1:

In this example, we have created a data frame of two attributes, first and second each containing 6 entities and further with the provided syntax and the call of the group_by() and the summarize() function passed with the attribute name and the data frame used to get the frequency table accordingly in the Rn language.

R




# Import the required library
library(dplyr)
  
# Created data frame
df <- data.frame(first=c(1,1,1,2,2,2),
                 second=c('a', 'a', 'b',
                          'a', 'c', 'd'))
  
# calculate frequency
df %>%
  group_by(first,second) %>%
  summarize(Freq=n())


Output:

  first second  Freq
  <dbl> <chr>  <int>
1     1 a          2
2     1 b          1
3     2 a          1
4     2 c          1
5     2 d          1

Example 2: 

In this example, we are using the in-built data frame of the R named:- “ToothGrowth” and will be creating the frequency table of the supp and the dose attribute of this data frame using the given syntax with the call of the group_by() and the summarize() function passed with the required parameters in the R language.

R




# Import the required library
library(dplyr)
  
# Created data frame
data("ToothGrowth")
df<-ToothGrowth
  
# calculate frequency
df %>%
  group_by(supp , dose) %>%
  summarize(Freq=n())


Output:

  supp   dose  Freq
  <fct> <dbl> <int>
1 OJ      0.5    10
2 OJ      1      10
3 OJ      2      10
4 VC      0.5    10
5 VC      1      10
6 VC      2      10


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads