简体   繁体   English

在单个列表中组合不同列表的数据帧

[英]combine data frames of different lists in a single list

I have two (or more) lists of the same number of data frames and want to combine my data frames of the different lists in a single list. 我有两个(或更多)相同数量的数据帧列表,并希望将不同列表的数据帧组合在一个列表中。 So as an output I want to get a single list of the same number of data frames as in each individual list. 因此,作为输出,我想获得与每个单独列表中相同数量的数据帧的单个列表。

Sounds a bit complicated, but basically I want to do this in an expandable and easier way: 听起来有点复杂,但基本上我想以可扩展和更简单的方式做到这一点:

d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
l1 <- list(d1,d2)
d3 <- data.frame(y1=c(11,22,33),y2=c(44,55,66))
d4 <- data.frame(y1=c(33,22,11),y2=c(66,55,44))
l2 <- list(d3,d4)

new_d1 <- do.call(rbind,list(l1[[1]],l2[[1]]))
new_d2 <- do.call(rbind,list(l1[[2]],l2[[2]]))
output <- list(new_d1,new_d2)

The output should than look like this: 输出应该如下所示:

> output
[[1]]
y1 y2
1  1  4
2  2  5
3  3  6
4 11 44
5 22 55
6 33 66

[[2]]
y1 y2
1  3  6
2  2  5
3  1  4
4 33 66
5 22 55
6 11 44

Additionally, which function can I use if l1 and l2 are already sitting in a list themselves? 另外,如果l1和l2已经位于列表中,我可以使用哪个功能?

I already looked at lapply() and sapply() , but both functions don't really fit. 我已经看过lapply()sapply() ,但这两个函数都不适合。 In the forums I only find solutions to combine a list of data frames in a single data frame. 在论坛中,我只找到在单个数据框中组合数据帧列表的解决方案。

In the simple case of l1 and l2 being lists in the global environment, you can use l1l2是全局环境中的列表的简单情况下,您可以使用

Map(rbind, l1, l2)

For the other case, when l1 and l2 are already sitting in a list , you can use 对于另一种情况,当l1l2已经位于list ,您可以使用

l <- list(l1, l2)
Reduce(function(...) Map(rbind, ...), l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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