Created
May 31, 2018 19:12
-
-
Save alandipert/ed28678b8427001786c3a700ec0f887f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# "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