Delete columns in the Tidean way

I would like to remove the column vector using dplyr> = 0.7

library(dplyr) data(mtcars) rem_cols <- c("wt", "qsec", "vs", "am", "gear", "carb") head(select(mtcars, !!paste0("-", rem_cols))) 

Error: rows must match column names. Unknown columns: -wt, -qsec, -vs, -am, -gear, -carb

dplyr <0.7 worked as follows:

 head(select_(mtcars, .dots = paste0("-", rem_cols))) # mpg cyl disp hp drat # Mazda RX4 21.0 6 160 110 3.90 # Mazda RX4 Wag 21.0 6 160 110 3.90 # Datsun 710 22.8 4 108 93 3.85 # Hornet 4 Drive 21.4 6 258 110 3.08 # Hornet Sportabout 18.7 8 360 175 3.15 # Valiant 18.1 6 225 105 2.76 

I tried all combinations of rlang: syms (), !!, !!!, quo and enquo that I can come up with ... help !?

+5
source share
3 answers

We can use one_of

  mtcars %>% select(-one_of(rem_cols)) 
+6
source

I would also use one_of() in this case, but as a rule, you need to create calls - with characters as an argument.

 # This creates a single call: call("-", quote(a)) # This creates a list of calls: syms(letters) %>% map(function(sym) call("-", sym)) 

Then you can combine the call list with !!!

+4
source
 drop = c("wt", "qsec", "vs", "am", "gear", "carb") mtcars %>% select_(.dots= setdiff(names(.),drop)) 
+1
source

Source: https://habr.com/ru/post/1269830/


All Articles