Last active
July 28, 2018 18:13
-
-
Save dalejbarr/5dd3099c1bc3d58b9cdfd07ff3c7fcfa 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
## join x and y, replacing any columns in x with matching columns from y | |
## x : the table with values to be replaced | |
## y : the table containing replacement values | |
## cols : the key columns (i.e., cols to join on) | |
replace_join <- function(x, y, cols) { | |
keep <- setdiff(names(x), names(y)) | |
dplyr::inner_join(dplyr::select_(x, .dots = c(cols, keep)), y, cols) | |
} | |
## like above, but: | |
## if an x row has no matching row in y, keep values from x | |
## NB: the common columns must have same data types | |
## also, does not check for unique match in y | |
patch_join <- function(x, y, cols) { | |
common <- intersect(names(x), names(y)) | |
keep_x <- setdiff(names(x), common) | |
df1 <- dplyr::inner_join(dplyr::select_(x, .dots = c(cols, keep_x)), | |
dplyr::select_(y, .dots = c(cols, common)), | |
cols) | |
dplyr::bind_rows(df1, dplyr::anti_join(x, df1, cols)) | |
} | |
## example: | |
## | |
## x <- data.frame(A = 1:3, B = 4:6, C = 7:9, D = 1:3) | |
## y <- data.frame(A = 1:2, C = 11:10, D = 5:4, E = letters[5:6]) | |
## replace_join(x, y, "A") | |
## patch_join(x, y, "A") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment