agstudy
agstudy

Reputation: 121568

Test if variable exists in data.table

I would like to do some computation in data.table that can columns names can vary.

library(data.table)
DT1 <- data.table(x=1:10,y=1:10)
DT1[,list(y+x)]

Now if I do the same thing for DT that don't contain y column:

DT <- data.table(x=1:10)
DT[,list(y+x)]

I will get an error. Of course I can do the check outside the data.table:

if("y" %in% names(DT))DT[,list(y+x)]

I wonder if there a way to test this with the data.table itself , something like :

DT[exists("y"),y+x]

Upvotes: 5

Views: 3056

Answers (1)

akrun
akrun

Reputation: 887098

We can use an if/else condition with exists

DT[, if(exists("y")) y+x else x]

If we have many variables to test, i.e. say 'y', 'z'

nm <- c('y', 'z')
DT[, if(Reduce(`&`, lapply(nm, exists))) y + z + x else x]

Upvotes: 6

Related Questions