Andy.Jian Andy.Jian - 16 days ago 4x
R Question

How to combine data.frame object in multiple list efficiently without duplication?

I have data.frame objects in multiple lists where some duplication exists. However, I intend to combine these data.frame object without duplication into one single list. I tried several ways to get expected output, but can't figure out how to combine data.frame object in multiple lists. Becuase in each list, the order of data.frame objects are very different. Does anyone know any trick of doing this manipulation easily? How can make this happen? any idea ? Thanks in advance.

This is quick reproducible example to run:

mini example:

myList_1 <- list(
foo = data.frame(from=c(2,7,11,19), to=c(5,10,14,24), label=c("a1","a3","a5","a8"), score=c(2,5,8,12)),
bar = data.frame(fom=c(12,17,21), to=c(15,19,25),label=c("b2","b3","b5"), score=c(7,3,6)),
cat = data.frame(from=c(3,9,17,27), to=c(5,13,21,42),lable=c("c1","c3","c6", "c11"), score=c(5,2,4,9))

myList_2 <- list(
bar = data.frame(from=c(7,12,27), to=c(10,15,36),label=c("b1","b2","b7"), score=c(4,7,11)),
foo = data.frame(from=c(19,31,48), to=c(24,37,59),label=c("a8","a10","a15"), score=c(12,3,7)),
cat = data.frame(from=c(6,17,22,27), to=c(12,21,25,42),label=c("c2","c6","c7","c11"), score=c(3,6,1,9))

myList_3 <- list(
cat = data.frame(from=c(17,22, 45), to=c(21,25,58),label=c("c6","c7","c17"), score=c(4,1,5)),
foo = data.frame(from=c(11,19,31,63), to=c(14, 24,37,71),label=c("a5","a8","a10","a19"), score=c(8,12,3,5)),
bar = data.frame(from=c(27,57,72), to=c(36,66,83),label=c("b7","b14","b22"), score=c(11,2,8))

my desired output :

myList <- list(
foo = data.frame(from=c(2,7,11,19,31,48,63),to=c(5,10,14,24,37,59,71),
label=c("a1","a3","a5","a8","a10","a15","a19"), score=c(2,5,8,12,3,7,5)),
bar = data.frame(from=c(7,12,17,21,27,57,72),to=c(10,15,19,25,36,66,83),
label=c("b1","b2","b3","b5","b7","b14","b22"), score=c(4,7,3,6,11,2,8)),
cat = data.frame(from=c(3,6,9,17,22,27,45),to=c(5,12,13,21,25,42,58),
label=c("c1","c2","c3","c6","c7","c11","c17"), score=c(5,3,2,4,1,9,5))

How can I get my output more easily/ efficiently ? How can I achieve my desired output ? Thanks a lot


We can do this with Map. Get the names of the first list ('myList_1') and use that to subset the other list elements so that it will be in the same order. Then we rbind the corresponding data.frames of each list elements with Map.

nm1 <- names(myList_1)
Map(rbind, myList_1, myList_2[nm1], myList_3[nm1])