Combine list and element from 2nd list while maintaining names in R

旧街凉风 提交于 2019-12-13 05:13:29

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/50767056/combine-list-and-element-from-2nd-list-while-maintaining-names-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!