I would like to check if a data.table
that my function is operating on is key
ed. 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
?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With