r - 如何遍历可能缺少节点的嵌套列表
问题描述
我正在从(非常嵌套的)json 源构建数据框。
我已经成功地映射了我要提取的列表元素,并且几乎可以!构建我想要的小标题。
除了缺少某些列表元素之外,如果没有数据。像这样(我想要chr
at 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 让我失望了。
解决方案
正如我所怀疑的那样,我拿错了。有一个.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_)
)
按预期工作。
推荐阅读
- azure - 提供对多个存储帐户的 Azure VM 访问
- amazon-web-services - 同时担任多个 IAM 角色如何工作?
- algorithm - FFMPEG色彩增强算法
- go - 创建通用渠道
- sql - snowflake-sql:min vs first_value windows函数的情况
- angular - 验证码会话空
- grafana - 如何将 Grafana 时间序列 - 轴值的软最大值分配给变量并在另一个仪表板面板中使用它?
- asynchronous - ReadAsync 只阻塞一次(一次读取),然后它不会在循环中再次阻塞
- java - 如何将 VideoView MediaController 添加到底部工作表对话框
- java - Spring JPA @Query JPQL 因“意外令牌:日期”而失败