【问题标题】:How to subset a list using map?如何使用地图对列表进行子集化?
【发布时间】:2018-01-20 22:23:03
【问题描述】:

我有以下清单:

list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))
[[1]]
[[1]][[1]]
[[1]][[1]]$name
[1] "John"


[[1]][[2]]
[[1]][[2]]$name
[1] "Jack" "Kate"

我只想提取name 的列表。我知道我可以使用

list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))%>% map(list(1, 'name'))

从第一个元素中提取名称。但是我如何从每个元素中提取name 来得到这个:

#[[1]]
#[1] "John"

#[[2]]
#[1] "Jack" "Kate"

更新:我刚刚意识到我可以使用flatten(),但是如何使用带有正确索引的地图呢?

【问题讨论】:

  • 你想要什么输出? x %>% flatten() %>% flatten()x %>% pluck(1) %>% map('name'),也许
  • @alistaire 我更新了我的回复

标签: r tidyverse purrr


【解决方案1】:

你可以在这里使用modify_depthpluckflatten,所有函数都来自purrr

your_list <- list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))

library(purrr)
modify_depth(your_list, .depth = 2, .f = pluck, "name") %>% 
 flatten()
#[[1]]
#[1] "John"

#[[2]]
#[1] "Jack" "Kate"

【讨论】:

  • 不知道pluck,但你的代码给了我一个错误Error in FUN(X[[i]], ...) : subscript out of bounds
  • 我用的是rvest::pluck。这个命名空间冲突有点出乎意料,我以为他们都属于tidyverse...
  • 确实如此。我不清楚为什么哈德利允许在他的包裹中发生这些冲突。
【解决方案2】:
mylist <- list(list(list(name = 'John'), list(name=c("Jack", "Kate"))))

library(purrr)

map(mylist[[1]], ~ .[[1]]) %>% 
  flatten_chr()

# [1] "John" "Jack" "Kate"

我假设您想要返回一个名称向量,而不是另一个列表。

编辑:没关系您想将其保留为列表。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2017-04-02
    • 2021-12-16
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多