Reputation: 375
I would like to create specific object based of 2 data frames. First contains basic information about students, second information how many points each student get in each day.
students <- data.frame(
studentId = c(1,2,3),
name = c('Sophia', 'Mike', 'John'),
age = c(13,12,15)
)
studentPoints <- data.frame(
studentId = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3),
date = rep(c(Sys.Date()+c(1:5)),3),
point = c(5,1,3,9,9,9,5,2,4,5,8,9,5,8,4)
)
As a result I would like to get object:
result <- list(
list(
studentId = 1,
name = 'Sophia',
age = 13,
details = list(
date = c("2021-04-11", "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15"),
point = c(5,1,3,9,9)
)
),
list(
studentId = 2,
name = 'Mike',
age = 12,
details = list(
date = c("2021-04-11", "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15"),
point = c(9,5,2,4,5)
)
),
list(
studentId = 3,
name = 'John',
age = 15,
details = list(
date = c("2021-04-11", "2021-04-12", "2021-04-13", "2021-04-14", "2021-04-15"),
point = c(8,9,5,8,4)
)
)
)
I created it manually, any idea how to create it automatically? because my database contains few thousands of students
Upvotes: 0
Views: 34
Reputation: 388982
Split the lists by studentId
, convert each column to it's own list and combine the datasets.
result <- Map(function(x, y) list(x, details = y),
lapply(split(students, students$studentId), as.list),
lapply(split(studentPoints, studentPoints$studentId), as.list))
Upvotes: 1