0

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

theforestecologist
  • 4,667
  • 5
  • 54
  • 91

1 Answers1

0

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
theforestecologist
  • 4,667
  • 5
  • 54
  • 91