我有两个列表,其元素的名称部分重叠,我需要将它们逐个元素合并/组合成一个列表:
> 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,它基本上按索引组合了两个列表(即:“[[”),而我需要按名称组合它们(即:“$”)。此外,由于列表具有不同的长度,因此应用了回收规则(结果相当不可预测)。
> 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
正如您可能想象的那样,我正在寻找的是:
$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
有没有办法做到这一点?谢谢!