将嵌套列表转换为数据框

4

我有一组列表存储在all_lists中。

all_list=c("LIST1","LIST2")

基于这些数据,我希望创建一个数据框,其中

LISTn$findings${Coli}$character 被输入到第 n 列,并使用 LISTn$rowname 作为行名。

数据

LIST1=list()
LIST1[["findings"]]=list(s1a=list(character="a1",number=1,string="a1type",exp="great"),
                        =list(number=2,string="b1type"),
                        in2a=list(character="c1",number=3,string="c1type"),
                        del3b=list(character="d1",number=4,string="d1type"))
LIST1[["rowname"]]="Row1"

LIST2=list()
LIST2[["findings"]]=list(s1a=list(character="a2",number=5,string="a2type",exp="great"),
                        s1b=list(character="b2",number=6,string="b2type"),
                        in2a=list(character="c2",number=7,string="c2type"),
                        del3b=list(character="d2",number=8,string="d2type"))
LIST2[["rowname"]]="Row2"

请注意,某些字符已丢失,可以使用“NA”来表示。
期望输出的是这个数据框:
       s1a  s1b in2a del3b 
Row1    a1   NA  c1   d1
Row2    a2   b2  c2   d2

这些列表大约有1000个,速度是一个因素。每个列表都在通过rjson::fromJSON(file=x)进行加载后大约为50mB。

行和列的名称没有遵循特定的模式。它们是名称和属性。

2个回答

6
我们可以使用一对组合循环遍历嵌套的并提取名称为"Row"的元素。
do.call(rbind, lapply(mget(all_list), function(x) 
  sapply(lapply(x$findings[grep("^Row\\d+", names(x$findings))], `[[`, 
      "character"), function(x) replace(x, is.null(x), NA))))

或者也可以通过将names更改为单个值,然后提取所有这些值来完成。

do.call(rbind, lapply(mget(all_list), function(x)  {
 x1 <- setNames(x$findings, rep("Row", length(x$findings)) )
 sapply(x1[names(x1)== "Row"], function(y) 
       pmin(NA, y$character[1], na.rm = TRUE)[1])}))

2

purrr拥有一个强大的函数,叫做map_chr,专门用于这些任务。

library(purrr)
sapply(mget(all_list),function(x) purrr::map_chr(x$findings,"character",.default=NA))
   %>% t
      %>% data.frame

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接