简体   繁体   English

将部分嵌套的列表转换为嵌套的 tibble

[英]Convert a partially nested list to a nested tibble

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.我想找到一种将部分嵌套列表转换为单行小标题的通用方法,以便原始 object 中的嵌套列表成为嵌套列表列。 For example, I need a function that could take this list as input:例如,我需要一个 function 可以将此列表作为输入:

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:并返回一个如下所示的 object:

> 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  
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 :如果您确实需要您的 output,请使用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]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM