purrr:如何提取列表元素的内容(而不是元素)
purrr: How to pluck a list element's contents (instead of the element)
在我有小标题列表的情况下,我有时会 purrr::keep()
多个元素,然后使用 reduce()
组合以得到小标题,但是当我 purrr::pluck()
或 purrr::keep()
只有一个,做一个 reduce 没有意义。获取小标题的最佳方法是什么,而不是包含小标题的列表元素?
我发现 keep() %>% enframe() %>% unnest()
在某些情况下有效,但在其他情况下无效,但无论如何看起来都很混乱。
其他尝试:
require(tidyverse)
#> Loading required package: tidyverse
mylist <- lst(cars, diamonds)
mylist %>% pluck("cars") %>% typeof
#> [1] "list"
mylist %>% pluck("cars") %>% as.tibble() %>% typeof
#> [1] "list"
mylist %>% pluck("cars")[1]
#> Error in .[pluck("cars"), 1]: incorrect number of dimensions
mylist %>% pluck("cars")[[1]]
#> Error in .[[pluck("cars"), 1]]: incorrect number of subscripts
mylist %>% pluck("cars") %>% unlist() %>% typeof
#> [1] "double"
mylist %>% pluck("cars") %>% unnest() %>% typeof
#> [1] "list"
mylist %>% pluck("cars") %>% flatten %>% typeof
#> [1] "list"
由 reprex package (v0.2.0) 创建于 2018-03-20。
目标是获得小费。
在我有小标题列表的情况下,我有时会 purrr::keep()
多个元素,然后使用 reduce()
组合以得到小标题,但是当我 purrr::pluck()
或 purrr::keep()
只有一个,做一个 reduce 没有意义。获取小标题的最佳方法是什么,而不是包含小标题的列表元素?
我发现 keep() %>% enframe() %>% unnest()
在某些情况下有效,但在其他情况下无效,但无论如何看起来都很混乱。
其他尝试:
require(tidyverse)
#> Loading required package: tidyverse
mylist <- lst(cars, diamonds)
mylist %>% pluck("cars") %>% typeof
#> [1] "list"
mylist %>% pluck("cars") %>% as.tibble() %>% typeof
#> [1] "list"
mylist %>% pluck("cars")[1]
#> Error in .[pluck("cars"), 1]: incorrect number of dimensions
mylist %>% pluck("cars")[[1]]
#> Error in .[[pluck("cars"), 1]]: incorrect number of subscripts
mylist %>% pluck("cars") %>% unlist() %>% typeof
#> [1] "double"
mylist %>% pluck("cars") %>% unnest() %>% typeof
#> [1] "list"
mylist %>% pluck("cars") %>% flatten %>% typeof
#> [1] "list"
由 reprex package (v0.2.0) 创建于 2018-03-20。
目标是获得小费。