1

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?

flpoirier
  • 41
  • 4
  • 4
    `?modifyList` .. – rawr Oct 30 '17 at 15:45
  • 1
    Did you meant `lst <- c(list1, list2); lst[!duplicated(lst)]` – akrun Oct 30 '17 at 15:46
  • @rawr, I learn something new every day. Frankly, I would never have thought to look for that function, but its utility is cut-and-dry. – r2evans Oct 30 '17 at 15:49
  • @akrun, that works perfectly, thanks – flpoirier Oct 30 '17 at 15:51
  • @rawr, thanks, I'll read about that – flpoirier Oct 30 '17 at 15:51
  • 1
    You say "Two lists will always have the same value for a given name", but is it also true that they *won't* have the same value for two *different* names? If not, then @akrun's suggestion might not be what you want. E.g., for `list1 <- list(a = 1)` and `list2 <- list(b = 1)`, that gives a result of `list(a=1)`. Whereas my answer below gives `list(a = 1, b = 1)` in that case. – Tim Goodman Oct 30 '17 at 16:07
  • @TimGoodman In my case, all values are unique, but you make a good point – flpoirier Oct 30 '17 at 16:15
  • `modifyList(list1,list2)` works well, @rawr please write as answer the world deserves to know – moodymudskipper Oct 30 '17 at 16:40

1 Answers1

1

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))])
Tim Goodman
  • 23,308
  • 7
  • 64
  • 83