Does a multi-value purrr::pluck exist?

丶灬走出姿态 提交于 2019-12-09 17:33:13

问题


Seems like a basic question and perhaps I'm just missing something obvious ... but is there any way to pluck a sublist (with purrr)? More specifically, here's an initial list:

l <- list(a = "foo", b = "bar", c = "baz")

And I want to return a new (sub-)list with only elements a and b. Normally, I'd just do 'base' R sub-listing:

l[c("a", "b")]

But this doesn't provide the nice .default handling of pluck. My understanding is that pluck 'replaces' [[, but is there a purrr equivalent for replacing [?


回答1:


I think that purrr::keep() does what you want.

l %>% keep(names(.) == "a" | names(.) == "b")




回答2:


There's clearly a need for "muti-value pluck". It really comes down to extending flexibility of "pluck" to retrieving multiple values from the same level of list, as described in this github issue. For the example above, you can probably get away with:

> purrr::map(purrr::set_names(c("a", "b")), 
          ~purrr::pluck(l, .x, .default = NA_character_))
#> $a
#> [1] "foo"
#> 
#> $b
#> [1] "bar"



回答3:


Similar to jzadra's post, you could also do:

l %>% keep(names(.) %in% c("a","b"))


来源:https://stackoverflow.com/questions/46983716/does-a-multi-value-purrrpluck-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!