Consider the following column selection in data.table :
library(data.table)
To streamline my code in some calculations with many and variable columns, I want to replace list(a,b) with a function. Here is the first attempt:
.ab <- function() quote(list(a, b)) dt[, eval(.ab())]
Ideally, I would like to get rid of eval() from the call to [.data.table and restrict it to the definition of .ab , while avoiding passing the dt data table to the .ab function,
.eab <- function() eval(quote(list(a, b))) dt[, .eab()]
What's happening? How can this be fixed?
I suspect that I was bitten by the R-lexical reach and the fact that the correct evaluation of list(a,b) relies on being in the J environment of the dt data table. Alas, I do not know how to get a link to the correct environment and use it as an envir or enclos in dt .
# .eab <- function() eval(quote(list(a, b)), envir = ?, enclos = ?)
EDIT
This approach almost works:
.eab <- function(e) eval(quote(list(a, b)), envir = e) dt[, .eab(dt)]
There are two drawbacks: (1) column names are not returned, (2) dt should be explicitly passed (which I would prefer to avoid). I would also prefer to avoid hardcoding dt as the environment of choice. These considerations lead to an alternative consideration to the above question: is there a software way to get the dt environment from within .eab ?
r data.table
Ryogi
source share