合并列表和第二个列表中的元素,同时保留R中的名称 [英] Combine list and element from 2nd list while maintaining names in R
本文介绍了合并列表和第二个列表中的元素,同时保留R中的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个列表与多个元素组合在一起,其中包含第二个列表中的一个元素. 但是,这样做时,我想保留一个合理的元素名称字符串.
我已经尝试过如何在R中组合两个列表的方法,但是它们不起作用. /p>
示例:
l1 <- list(foo = 1:5, bar = 1:5)
l2 <- list(abc = 1:5, xyz = 1:5)
l3 <- list(cat = 1:5, dog = 1:5)
我想要什么:
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc
[1] 1 2 3 4 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
尝试:
c(l1,l2,l3) #works fine if I want all elements from all lists (but I don't)
## My Other Attempts ##
c(l1,l2[['abc']],l3)
c(l1,abc = l2[['abc']],l3)
#But both don't work:
> c(l1,l2[['abc']],l3)
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
[[3]]
[1] 1
[[4]]
[1] 2
[[5]]
[1] 3
[[6]]
[1] 4
[[7]]
[1] 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
> c(l1,abc = l2[['abc']],l3)
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc1
[1] 1
$abc2
[1] 2
$abc3
[1] 3
$abc4
[1] 4
$abc5
[1] 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
我知道必须有一个简单的解决方案!
解决方案
您必须使用[]
不是 [[]]
l1 <- list(foo = 1:5, bar = 1:5)
l2 <- list(abc = 1:5, xyz = 1:5)
l3 <- list(cat = 1:5, dog = 1:5)
c(l1,l2['abc'],l3)
结果:
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc
[1] 1 2 3 4 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
I want to combine a list with multiple elements wih an element from a 2nd list. In doing so, however, I want to maintain a sensible string of element names.
I've tried the approaches from How to combine two lists in R, but they don't work.
Example:
l1 <- list(foo = 1:5, bar = 1:5)
l2 <- list(abc = 1:5, xyz = 1:5)
l3 <- list(cat = 1:5, dog = 1:5)
What I want:
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc
[1] 1 2 3 4 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
Attempts:
c(l1,l2,l3) #works fine if I want all elements from all lists (but I don't)
## My Other Attempts ##
c(l1,l2[['abc']],l3)
c(l1,abc = l2[['abc']],l3)
#But both don't work:
> c(l1,l2[['abc']],l3)
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
[[3]]
[1] 1
[[4]]
[1] 2
[[5]]
[1] 3
[[6]]
[1] 4
[[7]]
[1] 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
> c(l1,abc = l2[['abc']],l3)
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc1
[1] 1
$abc2
[1] 2
$abc3
[1] 3
$abc4
[1] 4
$abc5
[1] 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
I know there's got to be a simple solution to this!!
解决方案
You have to use []
not [[]]
l1 <- list(foo = 1:5, bar = 1:5)
l2 <- list(abc = 1:5, xyz = 1:5)
l3 <- list(cat = 1:5, dog = 1:5)
c(l1,l2['abc'],l3)
Results in:
$foo
[1] 1 2 3 4 5
$bar
[1] 1 2 3 4 5
$abc
[1] 1 2 3 4 5
$cat
[1] 1 2 3 4 5
$dog
[1] 1 2 3 4 5
这篇关于合并列表和第二个列表中的元素,同时保留R中的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文