问题
Suppose we have 3 list
s of data.frame
s. In BASE R, I was wondering how I could automatically (ex. in a looping structure) rbind
the data.frame
s 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