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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With