Remove columns with dplyr

Use modify_atand set columns to NULL which will remove them:

mtcars %>% modify_at(drop,~NULL)
#                    mpg cyl  hp    wt  qsec vs carb
# Mazda RX4         21.0   6 110 2.620 16.46  0    4
# Mazda RX4 Wag     21.0   6 110 2.875 17.02  0    4
# Datsun 710        22.8   4  93 2.320 18.61  1    1
# Hornet 4 Drive    21.4   6 110 3.215 19.44  1    1
# Hornet Sportabout 18.7   8 175 3.440 17.02  0    2
# Valiant           18.1   6 105 3.460 20.22  1    1
# ...

Closer to what you were trying, you could have tried magrittr::extract instead of dplyr::select

extract(mtcars,!names(mtcars) %in% drop) # same output

You can use -one_of(drop) with select:

drop <- c("disp", "drat", "gear", "am")
select(mtcars, -one_of(drop)) %>% names()
# [1] "mpg"  "cyl"  "hp"   "wt"   "qsec" "vs"   "carb"

one_of evaluates the column names in character vector to integers, similar to which(... %in% ...) does:

one_of(drop, vars = names(mtcars))
# [1]  3  5 10  9

which(names(mtcars) %in% drop)
# [1]  3  5  9 10

Tags:

R

Dplyr