按元素名称组合/合并列表 [英] Combine/merge lists by elements names

查看:29
本文介绍了按元素名称组合/合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,它们的元素名称部分重叠,我需要将它们逐个元素合并/组合成一个列表:

I have two lists, whose elements have partially overlapping names, which I need to merge/combine together into a single list, element by element:

> lst1 <- list(integers=c(1:7), letters=letters[1:5],
                words=c("two", "strings"))
> lst2 <- list(letters=letters[1:10], booleans=c(TRUE, TRUE, FALSE, TRUE),
                words=c("another", "two"), floats=c(1.2, 2.4, 3.8, 5.6))

> lst1
$integers
[1] 1 2 3 4 5 6 7

$letters
[1] "a" "b" "c" "d" "e"

$words
[1] "two"     "strings"

> lst2
$letters
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

$booleans
[1]  TRUE  TRUE FALSE  TRUE

$words
[1] "another" "two"    

$floats
[1] 1.2 2.4 3.8 5.6

我尝试使用mapply,它基本上按索引组合了两个列表(即:[["),而我需要按名称组合它们(即:$").此外,由于列表的长度不同,因此应用了回收规则(结果相当不可预测).

I tried using mapply, which basically combines the two lists by index (i.e.: "[["), while I need to combine them by name (i.e.: "$"). In addition, since the lists have different lengths, the recycling rule is applied (with rather unpredictable results).

> mapply(c, lst1, lst2)
$integers
 [1] "1" "2" "3" "4" "5" "6" "7" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

$letters
[1] "a"     "b"     "c"     "d"     "e"     "TRUE"  "TRUE"  "FALSE" "TRUE" 

$words
[1] "two"     "strings" "another" "two"    

$<NA>
 [1] 1.0 2.0 3.0 4.0 5.0 6.0 7.0 1.2 2.4 3.8 5.6

Warning message:
In mapply(c, lst1, lst2) :
  longer argument not a multiple of length of shorter

如您所想,我正在寻找的是:

As you might imagine, what I'm looking for is:

$integers
[1] 1 2 3 4 5 6 7

$letters
[1] "a" "b" "c" "d" "e" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

$words
[1] "two"     "strings"   "another" "two"

$booleans
[1]  TRUE  TRUE FALSE  TRUE

$floats
[1] 1.2 2.4 3.8 5.6

有什么办法可以实现吗?谢谢!

Is there any way to achieve that? Thank you!

推荐答案

您可以:

keys <- unique(c(names(lst1), names(lst2)))
setNames(mapply(c, lst1[keys], lst2[keys]), keys)

<小时>

泛化到任意数量的列表需要 do.calllapply 的混合:

l <- list(lst1, lst2, lst1)
keys <- unique(unlist(lapply(l, names)))
setNames(do.call(mapply, c(FUN=c, lapply(l, `[`, keys))), keys)

这篇关于按元素名称组合/合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆