将列表列表转换为数据框

Sha*_*hin 4 r list lapply dataframe purrr

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

all_list=c("LIST1","LIST2")
Run Code Online (Sandbox Code Playgroud)

从这些,我想创建一个数据框,这样

LISTn$findings${Coli}$character被输入到第 n 列,rowname from 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"
Run Code Online (Sandbox Code Playgroud)

请注意,缺少某些字符,NA 就足够了。

所需的输出是这个数据帧:

       s1a  s1b in2a del3b 
Row1    a1   NA  c1   d1
Row2    a2   b2  c2   d2
Run Code Online (Sandbox Code Playgroud)

这些列表大约有 1000 个,速度是一个因素。在我加载它们之后,每个列表大约有 50mBrjson::fromJSON(file=x)

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

akr*_*run 6

我们可以使用几种lapply/sapply组合来循环nestedlist并提取具有“Row”作为name

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))))
Run Code Online (Sandbox Code Playgroud)

或者也可以通过将 更改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])}))
Run Code Online (Sandbox Code Playgroud)