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.

2
  • if foo = c("a","b") what result do you want? Commented Feb 5, 2015 at 22:46
  • foo is always of the form rep(x ,n) where x \in letters Commented Feb 5, 2015 at 22:47

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.