Reputation: 5
I want to create a pivot table using R having more than one column. Image of My data.csv file and the desired result I want is as follows:
This is my sample data file.
The output what I want using R is:
The desired result can be easily obtained using pivot tables in excel but I want to use only R.
Upvotes: 0
Views: 71
Reputation: 1632
Three steps to do using base R , no package
data:
structure(list(`Registration Number` = structure(c(1L, 2L, 1L,
2L, 2L, 1L), .Label = c("123", "456"), class = "factor"), Name = structure(c(1L,
2L, 1L, 2L, 2L, 1L), .Label = c("a", "b"), class = "factor"),
Marks1 = c(20, 30, 40, 50, 60, 70), Marks2 = c(10, 20, 30,
40, 50, 60)), .Names = c("Registration Number", "Name", "Marks1",
"Marks2"), row.names = c(NA, -6L), class = "data.frame")
Lets use the aggregate
function
Step 1 - Calculate sum of Marks 1 by Registration Number
data1<-aggregate(Marks1 ~ `Registration Number`,dataf, sum)
Step 2 - Calculate sum of Marks 2 by Registration Number
data2<-aggregate(Marks1 ~ `Registration Number`,dataf, sum)
Step 3 - Merge the two together
dataset<-merge(data1,data2)
Registration Number Marks1 Marks2
1 123 130 100
2 456 140 110
Upvotes: 1
Reputation: 102
You can use the dplyr package
library(dplyr)
my_data %>%
group_by(rgistration_number,name)%>%
summarize(TotalMarks1=sum(marks1), TotalMarks2=sum(marks2))
Upvotes: 0