Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

r - 按名称删除数据框列(Drop data frame columns by name)

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.

(考虑到R的强大功能,我认为可能有比逐一删除每一列更好的方法。)

  ask by Btibert3 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(编辑:对于那些仍不熟悉索引函数的drop参数的用户,如果要保留一列作为数据框,请执行以下操作:)

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 .

(drop=TRUE (或不提及它)将删除不必要的尺寸,因此返回带有y列值的向量。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...