How to create boxplot of grouped data in R?

R ProgrammingServer Side ProgrammingProgramming

To create boxplot of grouped data in R, we would first need to convert the grouped data into complete data by repeating the values up to the frequency/count for each value and then use the boxplot function on the complete data.

Check out the below example to understand how it can be done.

Example

Following snippet creates a sample data frame −

Group<-1:5
Count<-sample(20:50,5)
df<-data.frame(Group,Count)
df

Output

The following dataframe is created −

  Group Count
1  1    49
2  2    47
3  3    29
4  4    25
5  5    37

In order to create boxplot of grouped data in R, add the following code to the above snippet −

Group<-1:5
Count<-sample(20:50,5)
df<-data.frame(Group,Count)
Complete_Data<-rep(df$Group,df$Count)
Complete_Data

Output

If you execute all the above given codes as a single program, it generates the following output −

[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
[38] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
[75] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
[112] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
[149] 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
[186] 5 5

In order to create boxplot of grouped data in R, add the following code to the above snippet −

boxplot(Complete_Data)

Output

If you execute all the above given codes as a single program, it generates the following output −

raja
Published on 06-Nov-2021 06:44:05

Advertisements