R 列表中的 rbind data.frames

rbind data.frames in a list in R

假设我们有 3 个 listdata.frame 个。在 BASE R 中,我想知道如何自动(例如在循环结构中)rbind 这 3 个列表中的 data.frames?

请注意,我想要循环结构,这样它就可以 rbind 更多数量的类似列表(例如 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)))

编辑:抱歉,我忽略了您想在 Base R 中解决这个问题

我不确定这是否正是您想要的,但您可以使用 purrr 中的函数 reduce 来达到此目的

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

这里有一个选项base R

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

或者用map

library(tidyverse)
mget(ls(pattern = "^g\d+$"))  %>% 
      map_dfr(~ pluck(., "b1") %>% 
                 extract2(1))