I use the following idiom for conditionally selecting columns from a data.frame:
DF = data.frame(a = 1:3,b = letters[1:3],c = LETTERS[1:3])
someCondition <- FALSE
# use `if(someCondition)` to conditionally include column 'c'
DF[,c('a','b',if(someCondition)'c')]
:> a b
:> 1 1 a
:> 2 2 b
:> 3 3 c
but the equivalent does not work with data.table's b/c NULL values are not dropped from lists the same way they are dropped from concatenation:
DT = as.data.table(DF)
DT[,.(a,b,if(someCondition)c)]
:> Error in setnames(jval, jvnames) :
:> Can't assign 3 names to a 2 column data.table
I've defined a function called ..
which is a work around:
.. <- function(...){
x = list(...)
x= x[!sapply(x,is.null)]
x
}
DT[,..(a,b,if(someCondition)c)]
:> V1 V2
:> 1: 1 a
:> 2: 2 b
:> 3: 3 c
but it seeks kind of kludgy to have to include my own function to accomplish an operation that is so common. Is there a more idiomatic way of conditionally selecting columns from a data.table?