I know you can use "indirection" when you use dplyr::select() inside a function:
myselect1 <- function( df, select_arg ) {
df %>%
select( {{ select_arg }} )
}
starwars %>%
myselect1( contains( '_color' ) ) %>%
head( n = 3 )
# hair_color skin_color eye_color
# <chr> <chr> <chr>
# blond fair blue
# NA gold yellow
# NA white, blue red
But, since you can only use a selection helper within a selecting function, if I want to make the selection conditional, I get an error:
myselect2 <- function( df, select_arg = NULL ) {
if( !is.null( select_arg ) ) {
df %>%
select( {{ select_arg }} )
} else {
df
}
}
starwars %>%
myselect2( contains( '_color' ) ) %>%
head( n = 3 )
# Error:
# ! `contains()` must be used within a *selecting* function.
# i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
# Backtrace:
# 1. starwars %>% myselect2(contains("_color")) %>% head(n = 3)
# 4. tidyselect::contains("_color")
# 6. tidyselect::peek_vars(fn = "contains")
How could I test whether the selection helper exists or not?
You have to
rlang::enquote the function argument. Afterwards you could check forNULLusingrlang::quo_is_null: