I don't understand why dplyr::coalesce
seems to fail when using tidyselect variables. Am I misunderstanding how tidyr::one_of
works?
# set up example
mtcars_new <- mtcars %>%
dplyr::mutate(cyl1 = ifelse(cyl == 4, cyl, NA)) %>%
dplyr::mutate(cyl2 = ifelse(cyl == 6, cyl, NA)) %>%
dplyr::mutate(cyl3 = ifelse(cyl == 8, cyl, NA))
# attempt coalesce with tidyselect
cyl_cols <- c("cyl1", "cyl2", "cyl3")
mtcars_tot <- mtcars_new %>%
dplyr::mutate(cyl_new = dplyr::coalesce(one_of(cyl_cols))) %>%
identity()
# coalesce succeeds when variables defined explicitly
mtcars_tot <- mtcars_new %>%
dplyr::mutate(cyl_new = dplyr::coalesce(cyl1, cyl2, cyl3)) %>%
identity()