【问题标题】:merge two data frames to single object of lists将两个数据框合并到列表的单个对象
【发布时间】:2021-04-10 07:53:57
【问题描述】:

我想根据 2 个数据框创建特定对象。第一个包含学生的基本信息,第二个信息是每个学生每天获得多少分。

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

结果我想得到对象:

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

我手动创建的,知道如何自动创建吗?因为我的数据库包含几千名学生

【问题讨论】:

  • 错误,我已经更正了

标签: r list dataframe


【解决方案1】:

studentId 拆分列表,将每一列转换为自己的列表并合并数据集。

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

【讨论】:

    猜你喜欢
    • 2015-04-18
    • 1970-01-01
    • 2021-11-07
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多