Passing function argument to data.table i

巧了我就是萌 提交于 2021-01-28 19:10:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!