How to create pivot table with sum for data stored in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To create pivot table with sum for data stored in R data frame, we can follow the below steps −

  • First of all, create a data frame with two categorical and one numerical column.

  • Then, use dcast function from reshape2 package to create pivot table for the data stored in data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
df

Output

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

 Group Gender Score
1  B  Male    69
2  B  Male    66
3  D  Male    34
4  D  Male    25
5  E  Male    51
6  B  Male    38
7  E  Male    48
8  A  Female  29
9  D  Male    10
10 C  Female  96
11 E  Female   8
12 D  Male    39
13 E  Female  94
14 D  Female  61
15 A  Female  70
16 B  Male    90
17 B  Female 100
18 B  Female  27
19 A  Female  33
20 A  Female  98
21 A  Male    32
22 B  Female  78
23 E  Male    86
24 D  Male    74
25 A  Female  99

Create pivot table

Using dcast function from reshape2 package to create pivot table for the data stored in data frame df −

Group<-sample(LETTERS[1:5],25,replace=TRUE)
Gender<-sample(c("Male","Female"),25,replace=TRUE)
Score<-sample(1:100,25)
df<-data.frame(Group,Gender,Score)
library(reshape2)
dcast(data=df,formula=Group~Gender,fun.aggregate=sum,value.var="Score")

Output

   Group Female Male
1  A      152   181
2  B      177   117
3  C       83    66
4  D      137    51
5  E      196   149
raja
Updated on 10-Nov-2021 06:46:20

Advertisements