Using tidyselect variables with dplyr::coalesce

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))) %>%

# coalesce succeeds when variables defined explicitly
mtcars_tot <- mtcars_new %>%
  dplyr::mutate(cyl_new = dplyr::coalesce(cyl1, cyl2, cyl3)) %>%

Turning cyl_cols into a list of symbols and then unquote-splicing it works:


mtcars_new %>%
  mutate(cyl_new = coalesce(!!!syms(cyl_cols)))

coalesce takes the ... argument, which suggests it requires unquote-splicing of a list of symbols (column names in this case). I'm not positive why the select helpers don't work, other than that coalesce isn't set up (like the select and rename functions) to work with the selection helpers.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.