首页 > 解决方案 > 如何遍历可能缺少节点的嵌套列表

问题描述

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

我已经成功地映射了我要提取的列表元素,并且几乎可以!构建我想要的小标题。

除了缺少某些列表元素之外,如果没有数据。像这样(我想要chrat position "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"))
   )

这返回

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 fu 让我失望了。

标签: rtidyversepurrrtibble

解决方案


正如我所怀疑的那样,我拿错了。有一个.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_)
)

按预期工作。


推荐阅读