R dplyr: Drop multiple columns

dplyrr

I have a dataframe and list of columns in that dataframe that I'd like to drop. Let's use the iris dataset as an example. I'd like to drop Sepal.Length and Sepal.Width and use only the remaining columns. How do I do this using select or select_ from the dplyr package?

Here's what I've tried so far:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% select(-drop.cols)

Error in -drop.cols : invalid argument to unary operator

iris %>% select_(.dots = -drop.cols)

Error in -drop.cols : invalid argument to unary operator

iris %>% select(!drop.cols)

Error in !drop.cols : invalid argument type

iris %>% select_(.dots = !drop.cols)

Error in !drop.cols : invalid argument type

I feel like I'm missing something obvious because these seems like a pretty useful operation that should already exist. On Github, someone posted a similar issue, and Hadley said to use 'negative indexing'. That's what (I think) I've tried, but to no avail. Any suggestions?

Best Answer

Check the help on select_vars. That gives you some extra ideas on how to work with this.

In your case:

iris %>% select(-one_of(drop.cols))