I only just realized that the OP is grabbing x
from the function's enclosing environment instead of passing it as an argument. I consider this bad practice and don't really have a recommendation for that case. I might delete this answer (which only covers passing x
to the function) if it's too much of a distraction.
library(data.table)
dt <- data.table(x=1:4,y=1:12)
ff = function(x, ...){
mDT = data.table(x)
dt[mDT, on=.(x), ...]
}
ff(4L, verbose = TRUE)
# Calculated ad hoc index in 0 secs
# Starting bmerge ...done in 0 secs
# x y
# 1: 4 4
# 2: 4 8
# 3: 4 12
This only addresses the OP's specific example, of DT[x == get("x", ...)]
, and not broader expressions. For those, constructing and evaluating an expression should work:
fs = function(x, ...){
e = substitute(x == ..x, list(..x = x))
dt[eval(e), ...]
}
fs(4L, verbose = TRUE)
# Creating new index 'x'
# Starting bmerge ...done in 0 secs
# x y
# 1: 4 4
# 2: 4 8
# 3: 4 12
fs(3L, verbose = TRUE)
# Using existing index 'x'
# Starting bmerge ...done in 0 secs
# x y
# 1: 3 3
# 2: 3 7
# 3: 3 11
The verbose output indicates that fs
creates indices, which can be helpful for speed. See vignette("datatable-secondary-indices-and-auto-indexing")
.
Eventually, there might be syntax so we can simply write ...
dt[..x == x]
perhaps using the proposed inherits = TRUE
argument from the link for safety (so that x
must be a column and either (i) x
must exist in the parent environment or ..x
must be a column name).