检查data.table是否键入函数R中

时间:2013-01-17 15:00:07

标签: r data.table

我想检查我的功能正在运行的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吗?

1 个答案:

答案 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
>

但你为什么需要呢?