6

Possible Duplicate:
remove an entire column from a data.frame in R

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

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

I've tried the following and I get errors:

> 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
Community
  • 1
  • 1
Blue Magister
  • 13,044
  • 5
  • 38
  • 56

2 Answers2

6

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

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
Chase
  • 67,710
  • 18
  • 144
  • 161
3

Try:

Orange[-match("age",names(Orange))]
   Tree circumference
1     1            30
2     1            58
3     1            87
4     1           115
...
James
  • 65,548
  • 14
  • 155
  • 193