使用子集从data.frame中删除列的列表 [英] removing a list of columns from a data.frame using subset

查看:136
本文介绍了使用子集从data.frame中删除列的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要从数据框架中删除列的列表。



我通常这样做:

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

哪个工作正常。



但是,我想使用子集以更干净的方式执行此操作。但它似乎是附加了data.frame,然后访问列名称作为变量,而不是字符串。



例如,这是我想要做的:

 子集(mtcars,select = -to.remove)

有没有办法强制子集 select 语句中使用字符串向量或者还有另一个更好的选择?

解决方案

我可能会这样做:

  to.remove<  -  c(hp,drat,wt,qsec)
`%ni%`&否定(`%in%`)
子集(mtcars,select = names(mtcars)%ni%to.remove)

(我使用%ni%很多,所以我已经建立在我的.Rprofile中。)


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

这篇关于使用子集从data.frame中删除列的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆