问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/28355372/passing-function-argument-to-data-table-i