将列表列表列表转换为数据框

时间:2019-12-26 23:53:21

标签: r list dataframe lapply purrr

我有一组存储在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 个答案:

答案 0 :(得分:5)

我们可以使用几个Access-Control-Allow-Origin组合来遍历lapply/sapply ed nest,并提取具有“行”的元素作为list

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)))) 更改为单个值然后提取所有这些值来完成

names

答案 1 :(得分:2)

purrr具有称为map_chr的强大功能,是为这些任务而构建的。

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