So I've found myself wanting to create a tibble from a list of lists. After using the inconcievably lovely transpose()
function from the purrr
package I've ended up with something structured like this, albeit much, much longer.
listi <- list("id" = list(list(708107), list(780583)),
"name" = list(list("Nessprettur"), list("Brekka")),
"distance" = list(list(444.46), list(902.376)))
Looking at this, I could of course create the tibble by hand, which wouldn't be a big deal for a very small list. Let's say my list is in fact only three variables and two observations.
It would be straight forward to do something like this:
library(tidyverse)
tidy_frame <- data_frame("id" = unlist(listi$id),
"name" = unlist(listi$name),
"distance" = unlist(listi$distance))
tidy_frame
# A tibble: 2 x 3
#id name distance
#<dbl> <chr> <dbl>
#708107. Nessprettur 444.
#780583. Brekka 902.
But of course, that is very problematic for a list that's, say, ten times longer than that. Perhaps I should do what I want to achieve through do.call()
and cbind()
?
list_column_frame <- data.frame(do.call(cbind, listi)) %>%
as_data_frame()
list_column_frame
# A tibble: 2 x 3
#id name distance
#<list> <list> <list>
#<list [1]> <list [1]> <list [1]>
#<list [1]> <list [1]> <list [1]>
list_column_frame %>% map_df(~unlist(.x))
# A tibble: 2 x 3
#id name distance
#<dbl> <chr> <dbl>
#708107. Nessprettur 444.
#780583. Brekka 902.
This certainly gets the job done and perhaps I should just be happy with getting the result I wanted. However, having watched Hadley's 5 minute intro to tidy eval, and Lionel's webinar on the subject, curiousity has gotten the better of me and I really want to know how I would write a function using tidy eval so that I could perhaps finally get tidy eval, even if just a tiny, tiny bit
I've tried countless variations on something like this (and none of them work - which makes sense as I well and truly don't know what I'm doing, despite everything in the aforementioned videos making sense to me when I see, for instance, Lionel doing it).
library(rlang)
library(glue)
listi_create <- function(x){
y <- sym(x)
eval_tidy(`$`(listi, y))
}
listi_create("id")
#NULL
names(listi) %>%
map_df(~data_frame(!!.x := listi_create(.x)))
#Error: Column `id` must be a 1d atomic vector or a list
What would be the correct approach to something like this? Any and all help appreciated.