我将一个JSON文件转换为一个带有嵌套列表结构的data.frame,我希望将其删除并展平.列表中的某些值为NULL,不接受这些值.如果我用只有NA值的data.frame结构替换NULL值,我会得到所需的结果.
以下是我的问题的简化示例.我试图用NA data.frame替换NULL值但由于嵌套结构而无法管理.我怎样才能达到预期的效果?
例
library(tidyr)
input1 <- data.frame(id = c("c", "d", "e"), value = c(7, 8, 9))
input2 <- NULL
input3 <- data.frame(id = c(NA), value = c(NA))
df <- dplyr::tibble(
a = c(1, 2),
b = list(a = input1, c = input2))
unnest(df)
Run Code Online (Sandbox Code Playgroud)
给出错误"错误:每列必须是向量列表或数据帧列表[b]"
df2 <- dplyr::tibble(
a = c(1, 2),
b = list(a = input1, c = input3))
unnest(df2)
Run Code Online (Sandbox Code Playgroud)
给出所需的输出.
Tho*_*s K 15
我们可以map_lgl从purrr这里使用.如果你不关心带有a的那些行NULL,你可以简单地用filter和删除它们unnest:
library(tidyverse)
df %>%
filter(!map_lgl(b, is.null)) %>%
unnest()
#> # A tibble: 3 x 3
#> a id value
#> <dbl> <fctr> <dbl>
#> 1 1 c 7
#> 2 1 d 8
#> 3 1 e 9
Run Code Online (Sandbox Code Playgroud)
如果你想保留这些行,你可以right_join在取消之后将它们带回来:
df %>%
filter(!map_lgl(b, is.null)) %>%
unnest() %>%
right_join(select(df, a))
#> Joining, by = "a"
#> # A tibble: 4 x 3
#> a id value
#> <dbl> <fctr> <dbl>
#> 1 1 c 7
#> 2 1 d 8
#> 3 1 e 9
#> 4 2 <NA> NA
Run Code Online (Sandbox Code Playgroud)
input1 <- data.frame(id = c("c", "d", "e"), value = c(7, 8, 9))
input2 <- NULL
input3 <- data.frame(id = c(NA), value = c(NA))
df <- dplyr::tibble(
a = c(1, 2),
b = list(a = input1, c = input2)
)
Run Code Online (Sandbox Code Playgroud)