简体   繁体   English

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

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

I have a tibble with one character column and one list-column that nests dataframes.我有一个包含一个字符列和一个嵌套数据框的列表列的小标题。 I want to collapse the dataframes in the list-column (using dplyr::bind_rows() ) and append the respective value from the character column for each row.我想折叠列表列中的数据框(使用dplyr::bind_rows() )和 append 每行的字符列中的相应值。

Example例子

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]>

I know how to collapse the entire items column:我知道如何折叠整个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

But what I'm trying to achieve is to paste the values from the category column of my_tibble to get:但我想要实现的是粘贴my_tibblecategory列中的值以获得:

desired output所需 output

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

How can I do this?我怎样才能做到这一点?


UPDATE更新


I think that tidyr::unnest_longer() brings me closer to the target:我认为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

But not sure how to progress.但不知道如何进步。 Trying to append with tidyr::unite() fails:尝试使用tidyr::unite()尝试 append 失败:

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. x 列items$item不存在。

unnest() returns an output that's easier to work with than unnest_longer() : unnest()返回一个比unnest_longer()更容易使用的 output :

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

It's not the nicer way, but it works.这不是更好的方法,但它有效。 Try this:尝试这个:

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

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

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