Skip to content

Instantly share code, notes, and snippets.

@francisbarton
Created January 12, 2025 22:13
Show Gist options
  • Select an option

  • Save francisbarton/f1f8ebb05b59727a46f0b78227bca814 to your computer and use it in GitHub Desktop.

Select an option

Save francisbarton/f1f8ebb05b59727a46f0b78227bca814 to your computer and use it in GitHub Desktop.
tidy_coalesce
#' 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