Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created May 17, 2023 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbarbone/6d5092635866d69d58ac44af67a43869 to your computer and use it in GitHub Desktop.
Save jmbarbone/6d5092635866d69d58ac44af67a43869 to your computer and use it in GitHub Desktop.
merge lists in R
merge_list <- function(x, y, keep = c("right", "left")) {
  keep <- match.arg(keep)
  stopifnot(is.list(x), is.list(y))
  x <- Filter(Negate(is.null), as.list(x))
  y <- Filter(Negate(is.null), as.list(y))
  c(x, y)[!duplicated(c(names(x), names(y)), fromLast = keep == "right")]
}


merge_list(
  list(a = 1, b = 2, c = NULL),
  list(a = 2, c = 3)
)
#> $b
#> [1] 2
#> 
#> $a
#> [1] 2
#> 
#> $c
#> [1] 3

merge_list(
  list(a = 1, b = 2, c = NULL),
  list(a = 2, c = 3),
  keep = "left"
)
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
#> 
#> $c
#> [1] 3

Created on 2023-05-17 with reprex v2.0.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment