按名称删除数据框列 [英] Drop data frame columns by name

查看:90
本文介绍了按名称删除数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我想从数据框中删除的列。我知道我们可以使用以下方式单独删除它们:

  df $ x<  -  NULL 

但是我希望通过较少的命令来执行此操作。



我知道我可以使用整数索引删除列:

  df < -  df [-c(1,3: 6,12)] 

但我担心我的变量的相对位置可能会改变。 p>

鉴于R的强大程度,我认为可能会比逐个删除每一列更好一些。

解决方案

您可以使用简单的名称列表:

  DF<  -  data.frame (
x = 1:10,
y = 10:1,
z = rep(5,10),
a = 11:20

drops< ; - c(x,z)
DF [,!(name(DF)%in%drops)]

或者,您可以按照以下名称列出这些列表:

 保持<  -  c( y,a)
DF [保持]

编辑:
对于仍然不熟悉索引功能的 drop 参数的人员,如果要保留一列作为数据框,请执行以下操作:

 保持<  - y
DF [,保持,drop = FALSE]

drop = TRUE (或不提及它)将丢弃不必要的维度,因此返回带值的向量的列 y


I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:

df$x <- NULL

But I was hoping to do this with fewer commands.

Also, I know that I could drop columns using integer indexing like this:

df <- df[ -c(1, 3:6, 12) ]

But I am concerned that the relative position of my variables may change.

Given how powerful R is, I figured there might be a better way than dropping each column one by one.

解决方案

You can use a simple list of names :

DF <- data.frame(
  x=1:10,
  y=10:1,
  z=rep(5,10),
  a=11:20
)
drops <- c("x","z")
DF[ , !(names(DF) %in% drops)]

Or, alternatively, you can make a list of those to keep and refer to them by name :

keeps <- c("y", "a")
DF[keeps]

EDIT : For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:

keeps <- "y"
DF[ , keeps, drop = FALSE]

drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

这篇关于按名称删除数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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