Skip to content

Instantly share code, notes, and snippets.

@carlganz
Created November 14, 2017 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlganz/a898142124331723448bd17d9b765dc7 to your computer and use it in GitHub Desktop.
Save carlganz/a898142124331723448bd17d9b765dc7 to your computer and use it in GitHub Desktop.
How to make list-cols?
library(dplyr)
library(tibble)
myList <- list(
list(
id = 1,
name = "A",
sublist = list(
a=1,b=2
)
),
list(id = 2,
name = "B",
sublist= list(
a=3,c=4
)
)
)
### This gets me what I want, but doesn't seem tidyverse enough
lapply(myList, function(x) {
x[vapply(x,is.list,logical(1))] <- lapply(x[vapply(x,is.list,logical(1))], function(i) {
list(i)
})
as_tibble(x)
}) %>% bind_rows
@hadley
Copy link

hadley commented Nov 14, 2017

I'd tackle it like this:

library(purrr)

myList <- list(
  list(
    id = 1,
    name = "A",
    sublist = list(
      a = 1, b = 2
    )
  ),
  list(
    id = 2,
    name = "B",
    sublist = list(
      a = 3, c = 4
    )
  )
)

tibble(
  id = myList %>% map_dbl("id"),
  name = yList %>% map_chr("name"),
  sublist = myList %>% map("sublist")
)

At some point in the future, we'll probably have something like:

read_tree(myList, cols = list(id = col_numeric(), name = col_character(), sublist = col_list())

And some tool for guessing the types so you can just do

read_tree(myList)

and get something reasonable

@carlganz
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment