Search code examples
rpurrr

How to append elements from second list to existent elements from first list in R


I have two lists x and y:

x <- list(id1 = list(a = list(t = 5)), id2 = list(a = list(t = 1), b = list(t = 3)), id3 = list(a = list(t = 1), b = list(t = 2)))

y <- list(b = list(k = 7))

I need to modify x list and add corresponding "b" elements from y list to obtain z list:

z <- list(id1 = list(a = list(t = 5)), id2 = list(a = list(t = 1), b = list(t = 3, k = 7)),
  id3 = list(a = list(t = 1), b = list(t = 2, k = 7)))

I try to use list_modify(x, y) and list_merge(x, !!!y) from purrr package but obtain wrong result. How to do this in R?


Solution

  • In this case you could do:

    result <- lapply(x, function(i) {
      if("b" %in% names(i)) i$b <- append(i$b, y$b); i;
      })
    
    

    Such that

    identical(result, z)
    #> [1] TRUE