Created
January 12, 2025 22:13
-
-
Save francisbarton/f1f8ebb05b59727a46f0b78227bca814 to your computer and use it in GitHub Desktop.
tidy_coalesce
This file contains hidden or 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
| #' A wrapper for dplyr::coalesce() that handles tidy column selections | |
| #' | |
| #' @param .data a data frame | |
| #' @param ... (use tidyselect specification) a selection of cols to coalesce | |
| #' @export | |
| tidy_coalesce <- function(.data, ..., res = "result", .after = NULL) { | |
| assert_that(inherits(.data, "data.frame")) | |
| cnms <- colnames(dplyr::select(.data, ...)) | |
| nms <- rlang::data_syms(cnms) | |
| aft <- ifnull(.after, dplyr::last(intersect(colnames(.data), cnms))) | |
| .data |> | |
| dplyr::mutate({{ res }} := dplyr::coalesce(!!!nms), .after = all_of(aft)) | |
| } | |
| #' An alternative to `%||%`, which I hate and can never remember | |
| #' | |
| #' @param x,y If `x` is NULL, will return `y`; otherwise returns `x`. | |
| #' @export | |
| ifnull <- function(x, y) { | |
| if (is.null(x)) y else x | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment