将函数参数传递给data.table i [英] Passing function argument to data.table i

查看:53
本文介绍了将函数参数传递给data.table i的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个data.table

Say we have a data.table

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

我想创建一个函数

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

如果...

foo <- rep("b", 6)

然后

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

基本上,我想将 id [[1]] 从执行环境传递到 myDT i 参数.

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.9.8,

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

这篇关于将函数参数传递给data.table i的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆