Removing a list of columns from a data.frame using subset

dataframer

I often need to remove lists of columns from a data.frame.

I usually do this:

to.remove <- c("hp","drat","wt","qsec")
mtcars[,-which(names(mtcars) %in% to.remove)]

which works fine.

But I'd like to be able to do this in a cleaner way using subset. But it seems to be attaching the data.frame and then accessing the column names as variables rather than strings.

For instance this is what I would like to be able to do:

subset(mtcars,select=-to.remove)

Is there a way to force subset to use a vectors of strings in the select statement? Or is there another better alternative?

Best Answer

I would probably do this like so:

to.remove <- c("hp","drat","wt","qsec")
`%ni%` <- Negate(`%in%`)
subset(mtcars,select = names(mtcars) %ni% to.remove)

(I use %ni% a lot, so I have it built into my .Rprofile already.)