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

I often need to remove column lists from data.frame.

I usually do this:

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

which works great.

But I would like to make it cleaner using subset . But it looks like it's a data.frame binding, and then access to the column names as variables, not rows.

For example, this is what I would like to do:

 subset(mtcars,select=-to.remove) 

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

+6
r dataframe
Mar 23 '12 at 20:12
source share
2 answers

I would do it like this:

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

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

+22
Mar 23 '12 at 20:22
source share
— -

Of course, you can use select, but you must pass names, not characters. So this will work:

 subset( mtcars, select = -c(hp, drat, wt, qsec) ) 
+4
Jul 03 '13 at 20:38
source share



All Articles