-1

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.

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:

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:

desired 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:

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:

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.

Emman
  • 3,695
  • 2
  • 20
  • 44

2 Answers2

1

unnest() returns an output that's easier to work with than 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
Emman
  • 3,695
  • 2
  • 20
  • 44
1

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)
Marcos Pérez
  • 1,260
  • 2
  • 7