Tidyeval: Dropping a column using Select( ) within a function?

I'm trying to drop a column through NSE with select( ). However, I cannot figure out how to keep the dash argument needed, along with the column name:

library(tidyverse)

t1 <- tibble(
  X1 = c(1,3,5,7,8,9,10,14,25,46,68,79),
  X2 = c(2,4,5,6,7,9,10,13,24,35,45,67),
  X3 = c(4,5,7,8,8,9,22,23,34,45,56,78)
)

select_tibble <- function(df,col){
  col <- enquo(col)
  df %>% select(-quo_name(col))
}

select_tibble(t1,X1)

'Error in -quo_name(col) : invalid argument to unary operator'

Pasting the dash in does not work either, instead select( ) looks for that entirely as the column name:

select_tibble <- function(df,col){
  col <- enquo(col)
  df %>% select(paste0("-",quo_name(col)))
}

select_tibble(t1,X1)

'Error: Strings must match column names. Unknown columns: -X1'
1 Like

If you use !! instead of quo_name it works:

library(tidyverse)

t1 <- tibble(
  X1 = c(1,3,5,7,8,9,10,14,25,46,68,79),
  X2 = c(2,4,5,6,7,9,10,13,24,35,45,67),
  X3 = c(4,5,7,8,8,9,22,23,34,45,56,78)
)

select_tibble <- function(df,col){
  col <- enquo(col)
  df %>% select(-!!col)
}

select_tibble(t1,X1)

Hopefully someone who understands this vignette more than I do can explain why this works :slight_smile:

1 Like

See this Stack Overflow answer:

You likely want to use rlang::lang.

@alexilliamson: Interesting -- didn't realize that it worked directly with !!.

1 Like

Fantastic, thank you.

1 Like

I'm not sure why, but for me personally, this blog helped tidy eval "click" a lot better than the vignette:

Might come in handy if you're trying to do more with tidy eval and function writing

3 Likes