r - How to select columns programmatically in a data.table? -
i have following data.table (dt):
dt <- data.table(v1 = 1:3, v2 = 4:6, v3 = 7:9)
i select subset of variables programmatically (dynamically), using object relevant variable names stored. example, want select 2 columns "v1" , "v3" stored in variable "keep"
keep <- c("v1", "v3")
if select "keep" columns data.frame, following work:
dt[keep]
unfortunately, not working when data.table. thought data.frame , data.table identical kind of behavior, apperently aren't. able advise on correct syntax?
this covered in faq 1.1, 1.2 , 2.17.
some possibilities:
dt[, c('v1','v3'), = false] dt[, c(1,3), = false] dt[, list(v1,v3)]
the reason df[c('v1','v3')]
works data.frame
covered in ?`[.data.frame`
data frames can indexed in several modes. when
[
,[[
used single vector index (x[i]
orx[[i]]
), index data frame if list. in usagedrop
argument ignored, warning.
from data.table 1.10.2
, may use ..
prefix when subsetting columns programmatically:
when
j
symbol prefixed..
looked in calling scope , value taken column names or numbers [...] experimental.
thus:
dt[ , ..keep] # v1 v3 # 1: 1 7 # 2: 2 8 # 3: 3 9