简体   繁体   中英

Element-wise rbind lists of dataframes in R

I have a list of 3 lists, each with an equal number of dataframes, 32, to be precise, and I wish to rbind them across the lists element-wise. To give a simpler example, suppose you have one list with 2 lists, each with 2 dataframes, like this:

[[1]]
[[1]][[1]]
  x  y
1 a 11
2 b 12
3 c 13

[[1]][[2]]
  x  y
1 a 14
2 b 15
3 c 16


[[2]]
[[2]][[1]]
  x  y
1 a 17
2 b 18
3 c 19

[[2]][[2]]
  x  y
1 a 21
2 b 22
3 c 23

given by:

A <- data.frame(c("a","b","c"), c(11,12,13))
colnames(A)<-c("x","y")
B <- data.frame(c("a","b","c"), c(14,15,16))
colnames(B)<-c("x","y")
C <- data.frame(c("a","b","c"), c(17,18,19))
colnames(C)<-c("x","y")
D <- data.frame(c("a","b","c"), c(21,21,23))
colnames(D)<-c("x","y")
L1 <- list(A,B)
L2 <- list(C,D)
L <- list(L1,L2)

How can I rbind the dataframes across the 2 lists element-wise, such that the final output is:

[[1]]
  x  y
1 a 11
2 b 12
3 c 13
4 a 17
5 b 18
6 c 19

[[2]]
  x  y
1 a 14
2 b 15
3 c 16
4 a 21
5 b 21
6 c 23

In this example, I could just output <- list(rbind(A,C),rbind(B,D))

But I want to do it for a much larger list of lists of dataframes

How about this:

A <- data.frame(c("a","b","c"), c(11,12,13))
colnames(A)<-c("x","y")
B <- data.frame(c("a","b","c"), c(14,15,16))
colnames(B)<-c("x","y")
C <- data.frame(c("a","b","c"), c(17,18,19))
colnames(C)<-c("x","y")
D <- data.frame(c("a","b","c"), c(21,21,23))
colnames(D)<-c("x","y")
L1 <- list(A,B)
L2 <- list(C,D)
L <- list(L1,L2)
lapply(1:2, \(i)rbind(L1[[i]], L2[[i]]))
#> [[1]]
#>   x  y
#> 1 a 11
#> 2 b 12
#> 3 c 13
#> 4 a 17
#> 5 b 18
#> 6 c 19
#> 
#> [[2]]
#>   x  y
#> 1 a 14
#> 2 b 15
#> 3 c 16
#> 4 a 21
#> 5 b 21
#> 6 c 23

Created on 2022-05-26 by the reprex package (v2.0.1)

One could just use transpose from purrr :

output <- lapply(purrr::transpose(L), 
                 function(l) do.call(rbind, args = l))
output

You can use map2 like this:

library(purrr)
map2(L1,L2,rbind)

Output:

[[1]]
  x  y
1 a 11
2 b 12
3 c 13
4 a 17
5 b 18
6 c 19

[[2]]
  x  y
1 a 14
2 b 15
3 c 16
4 a 21
5 b 21
6 c 23

Base R:

Map(rbind, L1, L2)
[[1]]
  x  y
1 a 11
2 b 12
3 c 13
4 a 17
5 b 18
6 c 19

[[2]]
  x  y
1 a 14
2 b 15
3 c 16
4 a 21
5 b 21
6 c 23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM