Created
June 21, 2017 21:49
-
-
Save alexpghayes/12ab5f7fc68acd000663698ced48e62f to your computer and use it in GitHub Desktop.
generalization of tidyr::unite
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
df <- tribble( | |
~ID, ~d1, ~d2, ~d3, | |
1, "G", "G", "C", | |
2, NA, "G", "T", | |
3, "A", NA, "G", | |
4, "G", "A", "A", | |
5, NA, NA, NA, | |
6, "G", "G", "G") | |
merge_chr <- function(df, col, ..., fun, remove = TRUE) { | |
to_merge <- quos(...) | |
col_name <- quo_name(enquo(col)) | |
merged <- dplyr::mutate(df, !!col_name := pmap_chr(list(!!!to_merge), fun)) | |
if (remove) merged <- dplyr::select(merged, -one_of(map_chr(to_merge, quo_name))) | |
merged | |
} | |
merge_chr(df, new, d1, d2, d3, fun = paste0) | |
first_non_na <- function(..., replacement) { | |
x <- list(...) | |
if (all(is.na(x))) return(replacement) | |
x[[min(which(!is.na(x)))]] | |
} | |
non_na <- purrr::partial(first_non_na, replacement = "*") | |
merge_chr(df, new, d1, d2, d3, fun = non_na) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment