1

Say we have a data.table

myDT <- data.table(id = c("a", "a", "b", "b", "c"), value = 1:5)
setkey(myDT, id)

I'd like to create a function

fun <- function(id) {
  ...
}

such that if

foo <- rep("b", 6)

then

fun(foo)
# I want this to return 3 4

Basically, I want to pass id[[1]] from the execution environment to the i argument of myDT.

I'm having a really hard time accessing the correct environment here and am looking for some help.

Changing the name of the function argument is not an option.

kevinykuo
  • 4,600
  • 5
  • 23
  • 31

1 Answers1

2

Strict control of scoping is scheduled for 1.9.8, #633, which when done will make accessing (external) variables which are also column names in your data.table easier.

But this is quite easy to get around. Not sure why you are having a really hard time..

fun <- function(id) {
    .id_unique = unique(id)
    myDT[.(.id_unique), which=TRUE]
}

fun(foo) # [1] 3 4
Arun
  • 116,683
  • 26
  • 284
  • 387
  • Indeed I did figure out how to get around this (though it took me embarrassingly long... ) but wanted to see how it could be done in general when there are name clashes – kevinykuo Feb 05 '15 at 22:53
  • Looking forward to implementation of that feature request. Have long dreamed of something like that, but didn't know until now it was actually being planned! – Josh O'Brien Feb 06 '15 at 02:42