Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select variables with multiple character vectors in data.table

I know we can select columns with a character vector in data.table with "..":

col = c("X1", "X2", "X3")
dt[, ..col]

However, it only works when we only use one character vector to select variables. What if I have multiple character vectors and wish to use all of them to select variables from data.table? Can I do it without merging the two vectors?

IV = c("X1", "X2", "X3")
DV = c("Y1", "Y2", "Y3")

dt[, ..(IV+DV)] gives an error "function .. doesn’t exist"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use c(.).

library(data.table)
MT <- as.data.table(mtcars)
var1 <- c("cyl", "disp")
var2 <- c("gear")
MT[,c(..var1, ..var2)][1:3,]
#      cyl  disp  gear
#    <num> <num> <num>
# 1:     6   160     4
# 2:     6   160     4
# 3:     4   108     4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading