Flatten list and push list key to vector on second level

后端 未结 2 1249
自闭症患者
自闭症患者 2021-01-28 13:21

I suppose this is simple, but I just can\'t seem to figure it out. I need to flatten the second level structure and push the list name/key to a vector on the same level as the

2条回答
  •  無奈伤痛
    2021-01-28 13:38

    myList can be turned into a data.frame using lapply() and rbindlist() from the data.table package:

    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
    

    Edit: This can be even more streamlined:

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

提交回复
热议问题