0

I have a variable list with column names and a dataframe . I would like to remove columns from the dataframes when the column names match the variable list.

columns -> "a","c"
dataframe->

a b c d  
0 0 1 1  
1 1 1 1  

Ouput->

b d  
0 1  
1 1

Please help me out with the solution.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

2

Update: Anders Swanson pointed out that you can now use select with standard evaluation. So the following works:

select(dataframe, -columns)

Previous version

You can use select_ together with '-' as shown below:

# create data 
columns <- c("a","c")
dataframe <- read.table(text="a b c d
0 0 1 1
1 1 1 1 ", header = TRUE)
# load dplyr package
require(dplyr)
# select columns
select_(dataframe, .dots = paste0("-", columns))
shadow
  • 21,823
  • 4
  • 63
  • 77
2

select_ is deprecated as of dplyr 0.7. See the select_ docs for more info.

I believe the new recommended approach is to use a select helper verbs.

Using shadow 's example. it would be: select(dataframe, -one_of(c("a", "b"))

Anders Swanson
  • 3,637
  • 1
  • 18
  • 43