从名称中删除数据框中的列 [英] Remove a column from a data frame by name

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

问题描述


可能重复:

有没有更好的方法从数据框架中删除列的名称,如下所示?

Is there a better way to remove a column by name from a data frame than the following?

Orange[colnames(Orange) != "Age"]

以下,我收到错误:

> Orange[-"Age"]
Error in -"age" : invalid argument to unary operator
> Orange[,-"Age"]
Error in -"age" : invalid argument to unary operator
> Orange[[,-"Age"]]
Error in -"age" : invalid argument to unary operator


推荐答案

您可以将列设置为NULL

You can set the column to NULL

> dat <- data.frame(a = 1, b = 1, c = 1)
> dat
  a b c
1 1 1 1
> dat$a <- NULL
> dat
  b c
1 1 1
> dat["b"] <- NULL
> dat
  c
1 1

有人会来,指出 data.frame 将会创建大量的数据副本来完成这个简单的任务。当数据变大(数百万行)时,这将花费大量时间,由于内存限制,可能无法正常工作。如果这将是一个问题,请使用 data.table := 运算符:

Someone will come along and point out that data.frame will makes lots of copies of the data to do this simple task. When data gets big (millions of rows), this will take a lot of time and may not work due to memory constraints. If that's going to be an issue, use data.table and the := operator:

library(data.table)
> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
     b c
[1,] 1 1

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

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