如果你试图通过字符串和命名变量来组合引用,你就会陷入困境。 (也可以通过引用函数内的“全局”变量)
最简单的方法是定义在哪里get
在寻找x
, (and y
)
这是重写的函数,以便您可以告诉它要查找的位置。
fun <- function(x,y,wherex=parent.frame(),wherey=parent.frame()) {
return(get(x,wherex) * get(y,wherey))
}
data.table
检查中存在的名称j
,并且仅加载所需的列。
在您的示例中,您不使用列名称,因此没有任何可用的内容。
如果你包括.SD
在表达式中j
,它将加载到所有列中。您可以使用.SD
as the wherex
/wherey
新定义的参数fun
DT[, lapply(c('x1', 'x2'), fun, y = 'y' , wherex=.SD, wherey=.SD)]
# V1 V2
# 1: -0.27871200 1.1943170
# 2: -0.68843421 -1.5719016
# 3: 1.06968681 2.8358612
# 4: 0.21201412 1.0127712
# 5: 0.05392450 0.2487873
# 6: 0.04473767 -0.1644542
# 7: 5.37851536 2.9710708
# 8: 0.23653388 0.9506559
# 9: 1.96364756 -1.4662968
# 10: -0.02458077 -0.1197023
请注意,您实际上并不需要将其包含在[.data.table
results <- setDT(lapply(c('x1','x2'), fun, y='y', wherex=DT,wherey=DT))
将返回相同的结果。