我有以下数据帧列表:
l = list()
l[[1]] = list(A=iris[1:3,], B=mtcars[1:3,])
l[[2]] = list(A=iris[5:8,], B=mtcars[5:8,])
我想做的是只连接列表的A
元素;导致:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
我试过这个,但它没有给我想要的:
> do.call(rbind, l)
A B
[1,] List,5 List,11
[2,] List,5 List,11
正确的方法是什么?
您可以尝试使用Reduce
和Map
。Map
将逐个绑定数据帧,而Reduce
确保它将对列表中的所有元素进行绑定。
Reduce(function(...)Map(function(x, y)rbind(x, y), ...), l)
$A
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
$B
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
使用purrr:的简单解决方案
purrr::map_dfr(l, "A")
或者只需使用lapply 调用"A"元素
do.call(rbind,lapply(l,"[[","A"))