4

我有以下讨厌的嵌套列表

编辑:更新包括value_I_dont_want

mylist <- list(
  list(
    nested_1 = list(
      nested_2 = list(
        list( value_I_want = "a", value_I_dont_want = "f"),
        list( value_I_want = "b", value_I_dont_want = "g")
      )
    )
  ),
  list(
    nested_1 = list(
      nested_2 = list(
        list( value_I_want = "c", value_I_dont_want = "h"),
        list( value_I_want = "d", value_I_dont_want = "i"),
        list( value_I_want = "e", value_I_dont_want = "j")
      )
    )
  )
)

我想得到所有value_I_want

我知道我可以在 for 循环中使用以下代码

mylist[[x]]$nested_1$nested_2[[y]]$value_I_want

但我想提高我的地图技能。我了解当列表是单级时如何使用map_chr,但我没有找到很多关于从非常嵌套的列表中提取的资源。我也知道我可以使用[[但没有找到合适的文档?

任何帮助表示赞赏!

4

2 回答 2

3

如果我们需要'yay's

library(purrr)
library(dplyr)
map(mylist, ~ .x$nested_1$nested_2 %>% unlist%>% grep("^yay", ., value = TRUE))

或者使用循环后pluck基于键'value_I_want'提取元素listmap

map(mylist, ~ .x$nested_1$nested_2 %>% 
                     map(pluck, "value_I_want") )
于 2020-03-29T17:37:41.330 回答
1

一个更通用的解决方案,要求我们只知道所需值的嵌套深度:

map(mylist, ~pluck(.,1,1) %>% map(pluck, "value_I_want")) 

第二个 pluck 在第一个 pluck 设置的嵌套级别上运行。

这也适用于缺少中间名称的嵌套列表,这在从 Internet 提取的 JSON 数据中很常见。

于 2021-08-24T22:04:12.937 回答