如何遍历可能缺少节点的嵌套列表

How do I iterate over a nested list, where nodes may be missing

我正在从(嵌套非常深的)json 源构建数据框。

我已经成功映射了我要提取的列表元素,差不多可以了!构建我想要的tibble。

除了部分列表元素缺失,如果没有数据。像这样(我想要 chr 在位置 "five",如果 NA 丢失,就像在第二个列表中一样):

nested_list  <- list(
    list(
        x = list(one = "this"),
        y = list(two = list(
                     three = list(
                           four = data_frame(
                                five = "is"))))),
   list(
       x = list(one = "a"),
       y = list(two = list(three = list()))))

如果缺少外部元素,我如何提供回退?我正在摸索 map_if,但想不出一个谓词函数来测试元素是否存在。我得到

Error: Predicate functions must return a single `TRUE` or `FALSE`, not NULL

到目前为止。

我想我有一个可重现的例子:

library("tidyverse")

nested_list  <- list(
    list(
        x = list(one = "this"),
        y = list(two = list(
                       three = list(
                               four = data_frame(
                                      five = "is"))))),
   list(
       x = list(one = "a"),
       y = list(two = list(three = list()))))

test_df <- nested_list %>%
    map(~ .x) %>%
    tibble(
        one = map_chr(., c("x", "one")),
        three = map_chr(., c("y", "two", "three", "four", "five"))
   )

这个returns

Error: Result 2 must be a single string, not NULL of length 0

我想在最后的标题中缺少一个值。

将 tibble 构造函数缩减为

test_df <- nested_list %>%
    map(~ .x) %>%
    tibble(
        one = map_chr(., c("x", "one")),
        three = map(., c("y", "two", "three"))
   )

在数据框的第二行给我 NULL 值;并且,正如预期的那样,第一行中有一个嵌套列表。 `map_df(., c("one","two", "three", "four")) 给我不均匀的列,tibble 构造失败。

我的 google 福让我失望了。

正如我所怀疑的那样,我的想法是错误的。有一个要映射的 .null 参数,就是为了这个目的。

所以:

test_df <- nested_list %>%
map(~ .x) %>%
tibble(
    one = map_chr(., c("x", "one")),
    three = map_chr(., c("y", "two", "three", "four", "five"), .null = NA_character_)
)

按预期工作。