如何在嵌套 list-column 中的 tibble 的字符列和行之间粘贴字符串

How to paste strings between tibble's character column and rows in a nested list-column

我有一个包含一个字符列和一个 list-column 嵌套数据框的标题。我想折叠 list-column 中的数据框(使用 dplyr::bind_rows())并为每一行附加字符列中的相应值。

例子

library(tibble)

my_tibble <-
  tibble(category = c("color", "shape"),
       items = list(tibble(item = c("red", "blue"), value = c(1, 2)), 
                    tibble(item = c("square", "triangle"), value = c(1, 2))
                    ))

> my_tibble
## # A tibble: 2 x 2
##   category items           
##   <chr>    <list>          
## 1 color    <tibble [2 x 2]>
## 2 shape    <tibble [2 x 2]>

我知道如何折叠整个 items 列:

library(dplyr)

my_tibble %>%
  pull(items) %>%
  bind_rows()

## # A tibble: 4 x 2
##   item     value
##   <chr>    <dbl>
## 1 red          1
## 2 blue         2
## 3 square       1
## 4 triangle     2

但我想要实现的是粘贴 my_tibblecategory 列中的值以获取:

期望输出

## # A tibble: 4 x 2
##   item               value
##   <chr>              <dbl>
## 1 color_red          1
## 2 color_blue         2
## 3 shape_square       1
## 4 shape_triangle     2

我该怎么做?


更新


我认为tidyr::unnest_longer()让我更接近目标:

library(tidyr)

my_tibble %>%
  unnest_longer(items)

# A tibble: 4 x 2
  category items$item $value
  <chr>    <chr>       <dbl>
1 color    red             1
2 color    blue            2
3 shape    square          1
4 shape    triangle        2

但不确定进展如何。尝试附加 tidyr::unite() 失败:

my_tibble %>%
  unnest_longer(items) %>%
  unite("category", `items$item`)

Error: Can't subset columns that don't exist.
x Column items$item doesn't exist.

unnest() returns 比 unnest_longer():

更容易处理的输出
library(tidyr)

my_tibble %>%
  unnest(items) %>%
  unite(col = item, category, item)

## # A tibble: 4 x 2
##   item           value
##   <chr>          <dbl>
## 1 color_red          1
## 2 color_blue         2
## 3 shape_square       1
## 4 shape_triangle     2

这不是更好的方法,但它确实有效。试试这个:

library(dlpyr)
my_tibble %>%
  group_by(category) %>%
  group_modify(~data.frame(.$items)) %>%
  ungroup() %>%
  mutate(item=paste(category,item,sep="_")) %>%
  select(-category)