按名称删除数据框列 [英] Drop data frame columns by name
问题描述
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屋!