1

Suppose we have 3 lists of data.frames. In BASE R, I was wondering how I could automatically (ex. in a looping structure) rbind the data.frames within these 3 lists?

Please note I want the looping structure so it can rbind any more number of similar lists (ex. g4 g5 ...)

g1 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))
g2 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))
g3 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

2 Answers2

1

Here is an option with base R

do.call(rbind, lapply(mget(ls(pattern = "^g\\d+$")), function(x) x$b1[[1]]))

Or with map

library(tidyverse)
mget(ls(pattern = "^g\\d+$"))  %>% 
      map_dfr(~ pluck(., "b1") %>% 
                 extract2(1))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • It depends on what the name of the identifier is - if you have named it as `h1, h2, h3 , ..`, then it would be `ls(pattern = "^h\\d+$")`. Here, `^` specifies the start of the string and `$` the end of the string, matching 'h' followed by one or more numbers (`\\d+`) – akrun May 19 '19 at 22:07
  • @rnorouzian If you have `xyz`, 'z15', 'g2z` etc, you may need to create a key of string identifiers by yourself. Or if these are the only objects loaded into the environment, `ls()` would be enough – akrun May 19 '19 at 22:09
0

EDIT: Apologize, I overlooked that you want to solve this in Base R

I am not sure if this is exactly what you want but you could use the function reduce from purrr for this purpose

library(tidyverse)
g1 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))
g2 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))
g3 <- list(b1 = list(data.frame(a = 1:3, b = 3:5)))

reduce(list(g1,g2,g3), rbind) %>%
  as_tibble() %>%
  unnest() %>%
  unnest()

# A tibble: 9 x 2
      a     b
  <int> <int>
1     1     3
2     2     4
3     3     5
4     1     3
5     2     4
6     3     5
7     1     3
8     2     4
9     3     5
MrNetherlands
  • 920
  • 7
  • 14
  • OP might look for `lst <- mget(paste0("g", 1:3)); out <- do.call(rbind, lapply(lst, function(x) x[[1]][[1]])); out` – markus May 19 '19 at 21:30