我想检查我的功能正在运行的data.table
是否为key
。怎么做到这一点?例如:
x = data.table(a=1:100, b=100:1)
setkey(x, a)
f = function(v) {v+1}
x[,f(b),by=a]
如果f
上有一个密钥集,x
是什么
key
这需要访问调用f
的对象,在本例中为x
。这可能在data.table
吗?
答案 0 :(得分:4)
f = function(v) {
cat("haskey(caller's x) is",eval(quote(haskey(x)), sys.frame(2)),"\n")
# x in line above = name of first argument to `[.data.table`
v+1
}
DT = data.table(a=1:3,foo=1:6)
DT[,f(foo),by=a]
haskey(caller's x) is FALSE
haskey(caller's x) is FALSE
haskey(caller's x) is FALSE
a V1
1: 1 2
2: 1 5
3: 2 3
4: 2 6
5: 3 4
6: 3 7
setkey(DT,a)
DT[,f(foo),by=a]
haskey(caller's x) is TRUE
haskey(caller's x) is TRUE
haskey(caller's x) is TRUE
a V1
1: 1 2
2: 1 5
3: 2 3
4: 2 6
5: 3 4
6: 3 7
>
但你为什么需要呢?