展平列表和将列表键推到第二层的向量 [英] Flatten list and push list key to vector on second level
问题描述
我想这很简单,但是我似乎无法弄清楚.
我需要展平第二层结构,并将列表名称/键推到与其他向量相同级别的向量. myList
的当前结构是
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 other vectors. The current structure of myList
is
$ 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
以此类推
我试图通过以下方式实现这一目标:
I've tried to achieve this by:
myList2 <- sapply(names(myList), function(y){
y <- unlist(c('ID' = y, myList[[y]]), use.names = TRUE)
})
但是我最终得到了我所需要的全部转置结果.我可以去t(myList2)
,但是我想了解如何正确执行此操作.谢谢!
But I end up with the full transposed result of what I need. I could go t(myList2)
but I want to understand how to do this correctly. Thank you!
可复制的数据:
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))
可以使用data.table
包中的lapply()
和rbindlist()
将
推荐答案
myList
转换为data.frame:
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
编辑:可以更加简化:
library(data.table)
rbindlist(myList, idcol = "ID")[, ID := names(myList)][]
这篇关于展平列表和将列表键推到第二层的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!