-1

I was wondering how it was possible to drop a number of columns from a dataframe/datatable using a vector of column names within a pipeline. Up until now I'm trying something like this:

del_cols <- c("colname 1", "colname 2", "colname 4")

new_data <- old_data %>%
     select_(del_cols)

However, this is not working. I also tried defining the columns to be removed as follows:

del_cols <- c("colname 1, colname 2, colname 4")

But this turned up to fail as well.

Any help would be appreciated!

Michael
  • 973
  • 12
  • 28

2 Answers2

2

In dplyr, use -one_of

cnames <- c("cyl", "disp", "mpg")
mtcars %>% select(-one_of(cnames)) %>% head

                   hp drat    wt  qsec vs am gear carb
Mazda RX4         110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     110 3.90 2.875 17.02  0  1    4    4
Datsun 710         93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 175 3.15 3.440 17.02  0  0    3    2
Valiant           105 2.76 3.460 20.22  1  0    3    1
Michael Veale
  • 871
  • 4
  • 11
1

This will drop the columns in del_cols

newdata<-old_data[,!names(old_data) %in% del_cols]
Jan Sila
  • 1,424
  • 3
  • 15
  • 31