rnorouzian
rnorouzian

Reputation: 7517

rbind data.frames in a list in R

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

Upvotes: 1

Views: 351

Answers (2)

akrun
akrun

Reputation: 886968

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

Upvotes: 0

MrNetherlands
MrNetherlands

Reputation: 940

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

Upvotes: 0

Related Questions