简体   繁体   中英

How do I merge two lists of mostly differing dataframes and bind the rows of those dataframes with the same name in R?

I have two different lists of dataframes. Some of the dataframes in the two lists have the same name, and others dont. When I merge the two lists, I need the dataframes with the same name to be merged rbind-style, and the ones that are unique in both lists just to remain as unique dataframes and tack on to the newly created merged list of dataframes.

The list1 is likely to have more dataframes and more rows per dataframe than list2 since it will be the cumulatively binded list as a result of a loop. List2 is the new result of each loop to be added to the cumulative list1.

Mock Example:

mydf1 <- data.frame(V1=1, V2=rep("A", 4)) 
mydf2 <- data.frame(V1=1, V2=rep("B", 3))
mydf3 <- data.frame(V1=1, V2=rep("C", 2))

mydf4 <- data.frame(V1=2, V2="A")
mydf5 <- data.frame(V1=3, V2="C")
mydf6 <- data.frame(V1=4, V2="D")
mydf7 <- data.frame(V1=7, V2="E")

list1 <- list(AA=mydf1, BB=mydf2, CC=mydf3)
list2 <- list(AA=mydf4, CC=mydf5, DD=mydf6, EE=mydf7)

Expected result:

$AA
  V1 V2
1  1  A
2  1  A
3  1  A
4  1  A
1  2  A

$BB
  V1 V2
1  1  B
2  1  B
3  1  B

$CC
  V1 V2
1  1  C
2  1  C
1  3  C

$DD
  V1 V2
1  4  D

$EE
  V1 V2
1  7  E

I have tried with the solution here , but have not been able to get them to work properly.

This solution isn't putting the right dataframes together and is creating other weird combinations.

(m <- match(names(list2), names(list1), nomatch = 0L))
# [1] 1 1 2
Map(rbind, list1[m], list2)

and this one appears to just never rbind the dataframes with the same names, all the dataframes just keep 1 row.

stackMe <- function(x) {
  a <- eval.parent(quote(names(X)))[substitute(x)[[3]]]
  rbind(list1[[a]], x)
} 
lapply(list2, stackMe)

How can I merge two list of dataframes where those dataframes with the same name just append/rbind the rows, and other unique dataframes are just tacked on to the list?

We can use indexing with Map

list1[names(list2)] <- Map(rbind, list1[names(list2)], list2)
list1
#$AA
#  V1 V2
#1  1  A
#2  1  A
#3  1  A
#4  1  A
#5  2  A

#$BB
#  V1 V2
#1  1  B
#2  1  B
#3  1  B

#$CC
#  V1 V2
#1  1  C
#2  1  C
#3  3  C

#$DD
#  V1 V2
#1  4  D

#$EE
#  V1 V2
#1  7  E

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