Question

In my work, I often refer to lists of variables as just one character vector.

A <- data.table(var1 = 1:10, var2 = 11:20, var3 = 21:30)
vecvar <- c("var1", "var2", "var3")

Whenever possible, I want to use vecvar rather than enumerate the variables, as this makes my code more robust to future applications to slightly different lists of variables.

I recently discovered data.table, and as much as I love the general elegance of the syntax and the efficiency gains, I find that it clashes a bit with my inclination outlined above. Indeed, A[, vecvar] won't work.

I am undecided as to the best way to work around this.

A[, vecvar, with=F] will work, but is not always convenient (e.g. A[, list(vecvar, var1+var2), with=F] won't work).

A[, sapply(vecvar, get)] won't work, though A[, sapply(vecvar, function(x) get(x))] will.

I am not stuck, as I have ways to deal with it -- I just want to know what the best way to work with this is, before I pick up bad habits!

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top