I would like to find a general method to convert a partially nested list to a one row tibble such that nested lists in the original object become nested list columns. For example, I need a function that could take this list as input:
my_list <- list(
thing_1 = "hello",
thing_2 = "world",
thing_3 = list(A=1,B=4,C=6,D=1),
thing_4 = list(foo="foo", bar="bar")
)
and return an object that looks like this:
> tribble(
~thing_1, ~thing_2, ~thing_3, ~thing_4,
"hello", "world", list(A=1,B=4,C=6,D=1), list(foo="foo", bar="bar")
)
# A tibble: 1 × 4
thing_1 thing_2 thing_3 thing_4
<chr> <chr> <list> <list>
1 hello world <named list [4]> <named list [2]>
Of course, this is not difficult for a specific input list, but I am looking for a solution that will work regardless of the content of the initial list. My initial attempts have involved various ways of trying to bind the top-level list items into columns, but my attempts all expand the nested list items into their own columns, which I do not want, eg:
> my_list |> purrr::map_dfc(~{.x})
# A tibble: 1 × 8
thing_1 thing_2 A B C D foo bar
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
1 hello world 1 4 6 1 foo bar
CodePudding user response:
as_tibble(list(v=list(my_list)))%>%unnest_wider(v)
# A tibble: 1 x 4
thing_1 thing_2 thing_3 thing_4
<chr> <chr> <list> <list>
1 hello world <named list [4]> <named list [2]>
Also
as_tibble(t(my_list))
# A tibble: 1 x 4
thing_1 thing_2 thing_3 thing_4
<list> <list> <list> <list>
1 <chr [1]> <chr [1]> <named list [4]> <named list [2]>
if you exactly need your output, use mutate
:
as_tibble(t(my_list)) %>%
mutate(across(where(~length(.x[[1]])==1), unlist))
# A tibble: 1 x 4
thing_1 thing_2 thing_3 thing_4
<chr> <chr> <list> <list>
1 hello world <named list [4]> <named list [2]>