6

I would like to remove a vector of columns using dplyr >= 0.7

library(dplyr)
data(mtcars)

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

Error: Strings 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've tried about all combinations of rlang:syms(), !!, !!!, quo and enquo that I can think of... help!?

Scott
  • 161
  • 8

4 Answers4

9

We can use one_of

 mtcars %>%
        select(-one_of(rem_cols))
akrun
  • 874,273
  • 37
  • 540
  • 662
6

I would also use one_of() in this case but more generally you have to create calls to - with the symbols as argument.

# This creates a single call:
call("-", quote(a))

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

You can then splice the list of calls with !!!

Lionel Henry
  • 6,652
  • 27
  • 33
2

The difficulty I had in doing precisely this task lead to me writing a package, friendlyeval, to simplify the tidy eval API. Here's an idea on how to do this using that:

library(friendlyeval)
library(dplyr)
data(mtcars)

rem_cols <- c("wt", "qsec", "vs", "am", "gear", "carb")
minus_cols <- paste0("-",rem_cols)
# [1] "-wt"   "-qsec" "-vs"   "-am"   "-gear" "-carb"

head(select(mtcars, !!!friendlyeval::treat_strings_as_exprs(minus_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

The one trap here is that you must use treat_strings_as_exprs() instead of treat_strings_as_cols(), since "-wt" is an expression involving a column name, not an actual column name.

MilesMcBain
  • 1,115
  • 10
  • 12
1
drop = c("wt", "qsec", "vs", "am", "gear", "carb")
 mtcars %>% 
    select_(.dots= setdiff(names(.),drop))
Prasanna Nandakumar
  • 4,295
  • 34
  • 63