How do I create a tibble or data.frame (with a source column) from a list of tibbles?

How would I create a large tibble from a list of tibbles?

For example:

library(tidyverse)

# create data
a <-  tibble(some_char = rep("pens", 4), some_int = (1:4))
b <-  tibble(some_char = rep("paper", 4), some_int = (5:8))

# list of tibbles
start <- list( 
  a,
  b
)

# tibble with source
end <- bind_rows(a %>% mutate(source = "a"),
                 b %>% mutate(source = "b"))
> start
[[1]]
# A tibble: 4 x 2
  some_char some_int
  <chr>        <int>
1 pens             1
2 pens             2
3 pens             3
4 pens             4

[[2]]
# A tibble: 4 x 2
  some_char some_int
  <chr>        <int>
1 paper            5
2 paper            6
3 paper            7
4 paper            8

> # tibble with source
> end <- bind_rows(a %>% mutate(source = "a"),
+                  b %>% mutate(source = "b"))
> end
# A tibble: 8 x 3
  some_char some_int source
  <chr>        <int> <chr> 
1 pens             1 a     
2 pens             2 a     
3 pens             3 a     
4 pens             4 a     
5 paper            5 b     
6 paper            6 b     
7 paper            7 b     
8 paper            8 b  

This seems to work:

library(purrr)
map_df(start, ~as_tibble(.x), .id="source")

# A tibble: 8 x 3
  source some_char some_int
  <chr>  <chr>        <int>
1 1      pens             1
2 1      pens             2
3 1      pens             3
4 1      pens             4
5 2      paper            5
6 2      paper            6
7 2      paper            7
8 2      paper            8
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.