在保留行数的同时解压 list-column 个 multi-row tibbles

Unpacking a list-column of multi-row tibbles while preserving the number of rows

我有一个小标题,其中一列是小标题列表。一些小问题 此列表不止一行。这是一个最小的例子:

library(tibble)
tmp <- tribble(
  ~x, ~y,
   1,  tibble(a=1,   b=2),
   2,  tibble(a=4:5, b=6:7))

产生

> tmp 
# A tibble: 2 x 2
      x y               
  <dbl> <list>          
1     1 <tibble [1 x 2]>
2     2 <tibble [2 x 2]>

我想创建一个行数与 tmp 相同的小标题,并且 根据需要将 list-column 扩展到尽可能多的列。在里面 例如,我想要

      x      a1      a2      b1      b2
  <int>   <dbl>   <dbl>   <dbl>   <dbl>
1     1       1      NA       2      NA
2     2       4       5       6       7

我曾想通过 unnest()pivot_wider()flatten() 的某种组合来做到这一点,但我无法完全实现它。执行此操作的最佳方法是什么?

在此示例中,list-column 中的小标题永远不会超过两行。但在我真实的 list-column 中,有些小标题只有一排,有些有两排,有些有两排以上。所以我正在寻找一种解决方案,当 list-column 中的 tibbles 具有任意数量的行时,它可以工作。

这是使用 unnest_wider

的一种解决方案
library(tidyr)
unnest_wider(tmp, y) %>% 
      unnest_wider(a, names_repair = ~gsub('...', 'a', .)) %>% 
      unnest_wider(b, names_repair = ~gsub('...', 'b', .))

New names:
* `` -> ...1
...
New names:
* `` -> ...1
* `` -> ...2
# A tibble: 2 x 5
      x    a1    a2    b1    b2
  <dbl> <dbl> <int> <dbl> <int>
1     1     1    NA     2    NA
2     2     4     5     6     7