如何有效地组合多个列表中的data.frame对象而不重复?

时间:2016-10-07 14:58:21

标签: r list dataframe

我在多个列表中有data.frame对象,其中存在一些重复。但是,我打算将这些data.frame对象无需复制组合到一个列表中。我尝试了几种方法来获得预期的输出,但无法弄清楚如何在多个列表中组合data.frame对象。因为在每个列表中,data.frame对象的顺序是非常不同的。有谁知道轻松做这个操作的任何技巧?如何实现这一目标?任何的想法 ?提前谢谢。

这是一个快速重现的例子:

迷你示例:

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))
)

我想要的输出:

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))
)

如何更轻松/高效地获取输出?如何实现我想要的输出?非常感谢

1 个答案:

答案 0 :(得分:2)

我们可以使用Map执行此操作。获取第一个列表的names(&#39; myList_1&#39;)并使用它来对其他列表元素进行子集化,以便它们的顺序相同。然后我们rbind list每个Map元素的相应data.frames。{/ p>

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