[英]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.我有一个包含 3 个列表的列表,每个列表都有相同数量的数据帧,准确地说是 32 个,我希望在列表中逐个元素地对它们进行
rbind
。 To give a simpler example, suppose you have one list with 2 lists, each with 2 dataframes, like this:举一个更简单的例子,假设您有一个包含 2 个列表的列表,每个列表有 2 个数据框,如下所示:
[[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:我怎样才能在 2 个列表中按元素
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
In this example, I could just output <- list(rbind(A,C),rbind(B,D))
在这个例子中,我可以
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)由reprex 包于 2022-05-26 创建 (v2.0.1)
One could just use transpose
from purrr
:可以只使用
purrr
的transpose
:
output <- lapply(purrr::transpose(L),
function(l) do.call(rbind, args = l))
output
You can use map2
like this:您可以像这样使用
map2
:
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:基数 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.