Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created May 31, 2018 19:12
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 alandipert/ed28678b8427001786c3a700ec0f887f to your computer and use it in GitHub Desktop.
Save alandipert/ed28678b8427001786c3a700ec0f887f to your computer and use it in GitHub Desktop.
# "Deep"-merges named lists, preferring values from y
deepMerge <- function(x, y) {
if (is.null(y)) return(x)
if (is.null(x)) return(y)
if (is.list(x) && is.list(y)) {
Reduce(function(merged, name) {
merged[[name]] <- deepMerge(x[[name]], y[[name]])
merged
}, union(names(x), names(y)), init = x)
} else y
}
identical(
deepMerge(
list(x = 1, y = 2),
list(z = 3)
),
list(x = 1, y = 2, z = 3)
)
# They aren't actually identical because reasons but you get the idea.
identical(
deepMerge(
list(x = 1, y = list(q = 2, z = 10)),
list(z = 3, y = list(q = 5, x = 23))
),
list(
x = 1,
z = 3,
y = list(
q = 5,
z = 10,
x = 23
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment