简体   繁体   中英

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?

I already looked at lapply() and sapply() , but both functions don't really fit. 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

Map(rbind, l1, l2)

For the other case, when l1 and l2 are already sitting in a list , you can use

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

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