R dplyr drop column that may or may not exist select(-name)

You can do:

diamonds %>% 
 select(-one_of("clarity"))

If there is a non-existing variable:

diamonds %>% 
 select(-one_of("clarity", "clearness"))

it returns a warning:

Warning message:
Unknown columns: `clearness` 

From dplyr 1.0.0, any_of() could be used:

diamonds %>% 
 select(-any_of(c("clarity", "clearness")))

Here's a slight twist using dplyr::select_if() that will not throw an Unknown columns: warning if the column name does not exist, in this case 'bad_column':

diamonds %>% 
  select_if(!names(.) %in% c('carat', 'cut', 'bad_column'))

Here's a simple modification to the one_of method shown by tmfmnk to work with symbols like select. The input is converted to quosures then to character.

library(tidyverse) # or just dplyr and purrr

drop_cols <- function(df, ...){
  df %>% 
    select(-one_of(map_chr(enquos(...), quo_name)))
}

diamonds %>% 
  drop_cols(clarity, color, zebra)

# # A tibble: 53,940 x 8
#    carat cut       depth table price     x     y     z
#    <dbl> <ord>     <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#  1 0.23  Ideal      61.5    55   326  3.95  3.98  2.43
#  2 0.21  Premium    59.8    61   326  3.89  3.84  2.31
#  3 0.23  Good       56.9    65   327  4.05  4.07  2.31
#  4 0.290 Premium    62.4    58   334  4.2   4.23  2.63
#  5 0.31  Good       63.3    58   335  4.34  4.35  2.75
#  6 0.24  Very Good  62.8    57   336  3.94  3.96  2.48
#  7 0.24  Very Good  62.3    57   336  3.95  3.98  2.47
#  8 0.26  Very Good  61.9    55   337  4.07  4.11  2.53
#  9 0.22  Fair       65.1    61   337  3.87  3.78  2.49
# 10 0.23  Very Good  59.4    61   338  4     4.05  2.39
# # ... with 53,930 more rows
# Warning message:
# Unknown columns: `zebra`

Tags:

Select

R

Dplyr