将列表和推送列表键展平为二级矢量

时间:2017-05-05 20:34:12

标签: r list transpose

我想这很简单,但我似乎无法弄明白。 我需要展平第二级结构并将列表名称/键推送到与其他向量相同级别的向量。 myList的当前结构是

$ 13454:List of 30
  ..$ subjectId        : num 187
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.911Z"
  ..$ n001             : num -999
  ..$ n002             : num -999
  ..$ gender           : num 1
  ..$ age              : num 18

 $ 13455:List of 30
  ..$ subjectId        : num 188
  ..$ procedureId      : num 3
  ..$ procedureSampleId: num 3
  ..$ timestamp        : chr "2017-04-21T17:15:10.913Z"
  ..$ n001             : num -999
  ..$ n002             : num -999      
  ..$ gender           : num -999
  ..$ age              : num 28

而这是我正在寻找的结构

 $ ID               : chr  '13455' '13455'
 $ subjectId        : num 187 188
 $ procedureId:     : num  3 3

等等

我试图通过以下方式实现这一目标:

  myList2 <- sapply(names(myList), function(y){
    y <- unlist(c('ID' = y, myList[[y]]), use.names = TRUE)
  })

但我最终得到了我需要的全部调换结果。我可以去t(myList2),但我想了解如何正确地做到这一点。谢谢!

编辑:可重复的数据:

myList <- list('13454' = list('subjectId' = 187, 'procedureId' = 3, 'procedureSampleId' = 3, 'timestamp' = "2017-04-21T17:15:10.911Z", 'n001' = -999, 'n002' = -999, 'gender' = 1, 'age' = 18), '13455' = list('subjectId' = 188, 'procedureId' = 3, 'procedureSampleId' = 3, 'timestamp' = "2017-04-21T17:15:10.913Z", 'n001' = -999, 'n002' = -999, 'gender' = -999, 'age' = 28))

1 个答案:

答案 0 :(得分:3)

可以使用myList包中的lapply()rbindlist()

data.table转换为data.frame:

result <- data.table::rbindlist(lapply(myList, as.data.frame), idcol = "ID")
result[["ID"]] <- names(myList)
result
#      ID subjectId procedureId procedureSampleId                timestamp n001 n002 gender age
#1: 13454       187           3                 3 2017-04-21T17:15:10.911Z -999 -999      1  18
#2: 13455       188           3                 3 2017-04-21T17:15:10.913Z -999 -999   -999  28

修改:这可以更精简:

library(data.table)
rbindlist(myList, idcol = "ID")[, ID := names(myList)][]