Skip to content

Instantly share code, notes, and snippets.

@alexpghayes
Created June 21, 2017 21:49
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 alexpghayes/12ab5f7fc68acd000663698ced48e62f to your computer and use it in GitHub Desktop.
Save alexpghayes/12ab5f7fc68acd000663698ced48e62f to your computer and use it in GitHub Desktop.
generalization of tidyr::unite
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