Rob*_*les 2 dictionary r list purrr
通过使用map()purrr 包中的各种函数,您可以将整数或字符串传递给函数并从子列表中提取元素。这些工作正如我所期望的那样:
listy <- list(A = list("silence", "cats", X = list(Aa = "dogs", "birds")),
B = list("silence", "fish-head", Y = list(Bb = "fish-face", "squirrel")))
> str(listy)
List of 2
$ A:List of 3
..$ : chr "silence"
..$ : chr "cats"
..$ X:List of 2
.. ..$ Aa: chr "dogs"
.. ..$ : chr "birds"
$ B:List of 3
..$ : chr "silence"
..$ : chr "fish-head"
..$ Y:List of 2
.. ..$ Bb: chr "fish-face"
.. ..$ : chr "squirrel"
list1 <- listy %>% map(1) %>% str # returns "silence" from A and B
list2 <- listy %>% map(2) %>% str # returns "cats" and "fish-head"
list3 <- listy %>% map(c(3, 1)) %>% str # returns "dogs" and "fish-face" from the lists X and Y within the list.
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何从该列表中提取多个元素?如果我想要 A 和 B 的“沉默”,以及 A 和 B 的“猫”和“鱼头”(换句话说,A 和 B 的元素 1 和 2),这可能map()吗?如果没有,最好的方法是什么?
这是我认为会起作用的:
list4 <- listy %>% map(1, 2) %>% str
Run Code Online (Sandbox Code Playgroud)
其中 1 指的是每个子列表中的第一个元素,而 2 指的是第二个。但这返回与 , 相同list1。使用c(1, 2)不起作用,因为它指的是嵌套结构(即[[1]][[2]])。我浏览了文档和通过谷歌找到的一些例子,但没有运气。有任何想法吗?
更新:我应该解释一下,理想情况下我希望能够按名称选择元素,如“沉默”。然而,这似乎效果不佳。(我有几个大列表,其中我想要更改的元素的位置)
像这样的东西?
library(purrr)
listy %>% map(., function(x) c(x[[1]], x[[2]]))
$A
[1] "silence" "cats"
$B
[1] "silence" "fish-head"
Run Code Online (Sandbox Code Playgroud)
要以 a 的形式获取输出data.frame,
listy %>% map_df(., function(x) c(x[[1]], x[[2]]))
# A tibble: 2 x 2
A B
<chr> <chr>
1 silence silence
2 cats fish-head
Run Code Online (Sandbox Code Playgroud)
或者,正如@Richard Scriven 所建议的那样,
map(listy, ~ unlist(.[1:2]))
Run Code Online (Sandbox Code Playgroud)