jzadra
jzadra

Reputation: 4314

purrr: How to pluck a list element's contents (instead of the element)

In cases where I have a list of tibbles, I sometimes purrr::keep() multiple elements and then combine using reduce() to end up with a tibble, however when I purrr::pluck() or purrr::keep() only one, doing a reduce doesn't make sense. What is the best way to get at the tibble, rather than the list element containing the tibble?

I've found that doing keep() %>% enframe() %>% unnest() works in some cases but not others, but it seems messy regardless.

Other attemps:

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"

Created on 2018-03-20 by the reprex package (v0.2.0).

The goal is to get the tibble.

Upvotes: 4

Views: 4456

Answers (1)

jzadra
jzadra

Reputation: 4314

Nothing like doing a bunch of reprex to solve your own (stupid) question!

Here's the deal for anyone else:

1) all tibbles will return "list" from typeof() (this is what threw me off)

2) keep is for multiple elements. Thus to get to a tibble, you'll have to do some kind of reduction (bind_rows, left_join, etc).

3) pluck is for single elements, and will return the element contents.

I stole this example from Hadley and updated with purrr functions:

enter image description here

Upvotes: 18

Related Questions