按重复名称合并列表列表中的内容

时间:2011-09-08 14:24:42

标签: r

鉴于列表列表,是否有一种优雅的方式将原始转换为处理?我使用简单的值,如1,2,3,但值可能是数据帧或其他。我们的目标不是重复删除每个唯一命名的内容,只需通过合并内容来重复删除名称。

original = structure(list(name1 = structure(list(one = 1, two = 2, three = 3), .Names = c("one", 
"two", "three")), name2 = structure(list(a = 9), .Names = "a"), 
    name1 = structure(list(four = 4, five = 5, six = 6), .Names = c("four", 
    "five", "six")), name2 = structure(list(b = 8), .Names = "b")), .Names = c("name1", 
"name2", "name1", "name2"))

treated = structure(list(name1 = structure(list(one = 1, two = 2, three = 3, 
    four = 4, five = 5, six = 6), .Names = c("one", "two", "three", 
"four", "five", "six")), name2 = structure(list(a = 9, b = 8), .Names = c("a", 
"b"))), .Names = c("name1", "name2"))

1 个答案:

答案 0 :(得分:5)

以下是使用plyr的解决方案。

require(plyr)
lnames  = names(original)
ulnames = unique(lnames)
treated = plyr::llply(ulnames, function(x) original[lnames == x])
treated = llply(treated, unlist, recursive = F)
names(treated) = ulnames