rbind data.frames in a list in R

孤人 提交于 2021-02-19 09:25:12

问题


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

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



回答2:


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


来源:https://stackoverflow.com/questions/56211943/rbind-data-frames-in-a-list-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!