r - 如何在嵌套列表列中的 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
不存在。
解决方案
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
推荐阅读
- android - onActivityResult() 使用自定义按钮返回空数据,但与返回正确数据的 onBackPressed() 完美配合
- java - 不明白 Linkedlist 节点指针如何指向其他节点?
- java - 未经检查的对类的调用
- javascript - 问题 - Base 64 PDF 字符串未在 IE 11 中呈现
- intellij-idea - 在 IntelliJ IDEA 中撤消 Windows Defender 提示的“不再显示”
- php - Use PHP Associative Array in If Condition
- android - 如何从firebase获取数据?
- javascript - 如何异步查询多条 SQL?
- reactjs - 出现错误:this.setState 不是反应中的函数
- javascript - 如何使用jquery获取span元素后的文本