Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

To get rid of a column named "foo" in a data.frame, I can do:

df <- df[-grep('foo', colnames(df))]

However, once df is converted to a data.table object, there is no way to just remove a column.

Example:

df <- data.frame(id = 1:100, foo = rnorm(100))

df2 <- df[-grep('foo', colnames(df))] # works

df3 <- data.table(df)

df3[-grep('foo', colnames(df3))] 

But once it is converted to a data.table object, this no longer works.

1 Answer

0 votes
by
edited by

To delete a column In a data table, you can use the := operator that modifies the input object by reference.

In your case:

library("data.table")

df <- data.frame(id = 1:100, foo = rnorm(100))

 head(df)

  id        foo

1  1 1.3011760

2  2 0.7567748

3  3 -1.7267304

4  4 -0.6015067

5  5 -0.3520465

6  6 0.7035239

To delete “foo” column in a data table you can use any one of the following:

dt <- data.table(df)

dt[,foo:=NULL]

#OR

dt[, grep("^foo$", colnames(dt)):=NULL]

head(dt)

Output: 

   id

1:  1

2:  2

3:  3

4:  4

5:  5

6:  6

Browse Categories

...