rdata.table

How to delete range of columns by first and last names in the range?


I can specify a range of columns in data.table using: first_col:last_col and can subset the data.table using that syntax. But if I want to set the same columns to NULL, data.table says it can't 'find' the columns (see below).

Why is that? And how can I delete a range of columns using "first_col:last_col" syntax?

library(data.table)

d <- data.table(a = 1:3, b = 4:6, c = 7:9)
#        a     b     c
#    <int> <int> <int>
# 1:     1     4     7
# 2:     2     5     8
# 3:     3     6     9

d[, b:c ]
#        b     c
#    <int> <int>
# 1:     4     7
# 2:     5     8
# 3:     6     9

d[, b:c := NULL ]
#Error in eval(lhs, parent.frame(), parent.frame()) : object 'b' not found

Solution

  • Here is using .SDcols:

    dt[, names(.SD) := NULL, .SDcols = b:c ]
    

    Relevant GitHub issue #6170