问题
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