Flatten list and push list key to vector on second level

后端 未结 2 1226
自闭症患者
自闭症患者 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:36

    Edit: To get to the list format you indicate above in base R, use rbind to build the data frame, then unlist the necessary elements with lapply.

    With your list above, you can use do.call to call rbind in base R:

    example<-data.frame(ID = as.character(names(myList)), do.call("rbind", myList), row.names = NULL)
    exAsList <-lapply(example, function(x) x <- unlist(x, use.names = FALSE))
    exAsList
    
    0 讨论(0)
  • 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)][]
    
    0 讨论(0)
提交回复
热议问题