首页 > 解决方案 > 如何在嵌套列表列中的 tibble 的字符列和行之间粘贴字符串

问题描述

我有一个包含一个字符列和一个嵌套数据框的列表列的小标题。我想折叠列表列中的数据框(使用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

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

期望的输出

## # 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`)

错误:不能对不存在的列进行子集化。
x 列items$item不存在。

标签: rstringdplyrtidyrtibble

解决方案


unnest()返回比以下更容易使用的输出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

推荐阅读