flpoirier
flpoirier

Reputation: 41

Combining named lists in R, taking only one value from each

Simple question, but I can't seem to find an answer:

I have two lists, with overlapping names. Two lists will always have the same value for a given name, like so:

list1 ->

  $col_a
  [1] "a"

  $col_b
  [1] "b"

  $col_c
  [1] "c"

list2 ->

  $col_b
  [1] "b"

  $col_c
  [1] "c"

  $col_d
  [1] "d"

Combining them, as in this answer, gives me the following:

$col_a
[1] "a"

$col_b
[1] "b" "b"

$col_c
[1] "c" "c"

$col_d
[1] "d"

Instead, I would like:

$col_a
[1] "a"

$col_b
[1] "b"

$col_c
[1] "c"

$col_d
[1] "d"

How do I do this?

Upvotes: 1

Views: 114

Answers (1)

Tim Goodman
Tim Goodman

Reputation: 23986

If i understand what you're asking, you could take all the elements from the first list, and combine them with all the elements from the second list whose names don't occur in the first list:

c(list1, list2[!(names(list2) %in% names(list1))])

Upvotes: 1

Related Questions