Home > Blockchain >  Select variables with multiple character vectors in data.table
Select variables with multiple character vectors in data.table

Time:11-02

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"

CodePudding user response:

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
  • Related