3

What is the best practice to delete columns programmatically in data.table?

The following works:

DT[, c("a", "b") := NULL]

But when trying to do this using a variable that stores column names

cols.to.del <- c("a", "b")
DT[, cols.to.del := NULL]

it fails badly as cols.to.del is not evaluated in the correct environment.

paljenczy
  • 4,779
  • 8
  • 33
  • 46

1 Answers1

7

We can wrap it inside the brackets, and then assign (:=) to 'NULL' (preferred way)

DT[, (cols.to.del) := NULL]

Or another option (in case we don't want to wrap it with brackets) would be to loop over the 'cols.to.del' in a for loop and assign to NULL

for(j in seq_along(cols.to.del)){
    DT[, cols.to.del[j] := NULL]
}

Or for subsetting the columns, we can use setdiff along with with=FALSE.

DT[, setdiff(names(DT), cols.to.del), with=FALSE]
akrun
  • 874,273
  • 37
  • 540
  • 662