2

Is that possible to delete multiple columns by reference using data.table?

None of the following works

library(data.table);
dt <- mtcars %>% setDT

# THESE ARE NOT RUNNABLE
dt[, range := NULL, with = F]
dt[, (range) := NULL, with = F]
dt[, ..range:=NULL]
dt[, ':='(.SD=NULL), .SDcols=range] 
dt[, lapply(.SD, NULL), .SDcols=range] 
dt[, ':='(mget(range)):=NULL]

Can you help?

PS. Eventually, for each of the lines above to I would like to know when it can or when it cannot be used (evidently, they can't be used for deleting a range of columns, but they can be used for selecting , or assigning values to, a range of columns)

1
  • 8
    What is range. Perhaps range <- c("mpg", "cyl"); > dt[, (range) := NULL]; names(dt) [1] "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb" Commented Dec 8, 2021 at 19:35

3 Answers 3

2

Try this:

library(data.table)

dt = data.table(mtcars)

dt[, `:=`(wt=NULL, hp=NULL, disp=NULL, am=NULL, gear=NULL, carb=NULL)]

Output:

> head(dt)
    mpg cyl drat  qsec vs
1: 21.0   6 3.90 16.46  0
2: 21.0   6 3.90 17.02  0
3: 22.8   4 3.85 18.61  1
4: 21.4   6 3.08 19.44  1
5: 18.7   8 3.15 17.02  0
6: 18.1   6 2.76 20.22  1

Or as akrun wrote:

range = c("wt", "hp", "disp", "am", "gear", "carb")
dt[, (range):=NULL]
Sign up to request clarification or add additional context in comments.

Comments

1

If range is something like 1:3 then you could do...

range<-1:3

DT1[,(names(DT1)[range]):=NULL]

or

set(DT1, j=range, value=NULL)

Comments

0

I know this is a very old post now, but if range is a vector of column names you'd like to remove, you can do this:

DT<-DT[,.SD,.SDcols=-range]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.