使用所有递归索引作为列名将嵌套列表转换为 data.frame,并用 NA 填充缺失的列

Convert nested lists to data.frame using all recursive indexes as colnames and fill missing columns with NAs

我已经为此苦苦挣扎了一天,在 SO 中进行的所有研究似乎都没有产生我需要的结果。

我有这个列表:

    input_list <- list(
        list(A = 'a1', B = 'b1', C = 'c1', D = 'd1'),
        list(A = 'a2', C = 'c2', D = 'd2'),
        list(A = 'a3', B = 'b3', C = 'c3'),
        list(A = 'a4', B = 'b4', C = 'c4', 
             D = list(
                sub_1 = "d4_1",
                sub_2 = "d4_2")
             )
    )

基本上我想把它变成这样的结构:

#tbl_df
#A  B  C  D  D.sub_1  D_sub_2
#a1 b1 c1 d1 NA       NA
#a2 NA c2 d2 NA       NA
#a3 b3 c3 NA NA       NA
#a4 b4 c4 NA d4_1     d4_2

我试过乱用地图功能:

output_list <- input_list %>% 
    map(unlist) %>% 
    do.call(rbind.data.frame, .)

它正确地取消列出所有嵌套列表,将它们转换为命名向量,但我不知道如何 rbind 匹配列名的行并用 NA 填充缺失的变量。

感谢任何帮助。

也许试试这个。您可以使用 unlist()lapply() 来取消嵌套值,然后使用 as.data.frame(t(...)) 将每个元素转换为数据框。最后,dplyr 中的 bind_rows() 可以按照您的预期绑定元素。这里的代码:

library(dplyr)
#Code
newdf <- bind_rows(lapply(input_list, function(x) as.data.frame(t(unlist(x)))))

输出:

   A    B  C    D D.sub_1 D.sub_2
1 a1   b1 c1   d1    <NA>    <NA>
2 a2 <NA> c2   d2    <NA>    <NA>
3 a3   b3 c3 <NA>    <NA>    <NA>
4 a4   b4 c4 <NA>    d4_1    d4_2

您可以使用 map_dfr :

purrr::map_dfr(input_list, as.data.frame)

#   A    B  C    D D.sub_1 D.sub_2
#1 a1   b1 c1   d1    <NA>    <NA>
#2 a2 <NA> c2   d2    <NA>    <NA>
#3 a3   b3 c3 <NA>    <NA>    <NA>
#4 a4   b4 c4 <NA>    d4_1    d4_2

我们可以使用unnest_wider

library(purrr)
library(dplyr)
tibble(col = input_list) %>% 
     unnest_wider(c(col)) %>%
     unnest_wider(c(D))