簡體   English   中英

將兩個數據幀合並到列表的單個 object

[英]merge two data frames to single object of lists

我想基於 2 個數據幀創建特定的 object。 第一個包含有關學生的基本信息,第二個信息是每個學生每天獲得多少分。

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)
)

結果我想得到 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)
    )
  )
)

我手動創建的,知道如何自動創建嗎? 因為我的數據庫包含幾千名學生

studentId拆分列表,將每列轉換為其自己的列表並組合數據集。

result <- Map(function(x, y) list(x, details = y), 
              lapply(split(students, students$studentId), as.list), 
              lapply(split(studentPoints, studentPoints$studentId), as.list))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM