Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing a list of columns from a data.frame using subset [duplicate]

Tags:

dataframe

r

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?

like image 579
Jesse Avatar asked Mar 23 '12 20:03

Jesse


1 Answers

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.)

like image 139
joran Avatar answered Sep 28 '22 08:09

joran