Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a data.table is keyed in a function, R

Tags:

r

data.table

I would like to check if a data.table that my function is operating on is keyed. How does one do this? For example:

x = data.table(a=1:100, b=100:1)
setkey(x, a)
f = function(v) {v+1}
x[,f(b),by=a]

I would like to check inside f if there is a key set on x and what that key is

This would require access to the object that f was called from, in this case x. Is this possible in data.table?

like image 899
Alex Avatar asked Oct 05 '22 08:10

Alex


1 Answers

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
>

But why would you need that?

like image 170
Matt Dowle Avatar answered Oct 13 '22 11:10

Matt Dowle