在没有“with"的情况下对 data.table 进行键控查找 [英] Keyed lookup on data.table without 'with'
问题描述
我有一个像这样的 data.table
结构(除了我的非常大):
I have a data.table
structure like so (except mine is really huge):
dt <- data.table(x=1:5, y=3:7, key='x')
我想通过名称为 x
的另一个变量查找该结构中的行(注意 - 与 dt
):
I want to look up rows in that structure by another variable whose name is x
(notice - the same as the name of the key of dt
):
x <- 3:4
dt2 <- dt[ J(x) ]
这行不通,因为查找首先看到的是列名,局部变量被遮住了:
This doesn't work, because the lookup sees the column name first, and the local variable is obscured:
dt2
# x y
# 1: 1 3
# 2: 2 4
# 3: 3 5
# 4: 4 6
# 5: 5 7
我考虑了 [.data.table
的 with
参数,但这仅适用于 j
参数,而不适用于 i
参数.
I thought about the with
argument for [.data.table
, but that only applies to the j
argument, not the i
argument.
i
参数是否有类似的东西?
Is there something similar for the i
argument?
如果没有,每当我使用局部变量并且我不知道 dt
中列名的完整列表时,这样的事情会很方便,以避免冲突.
If not, such a thing would be handy whenever I'm using a local variable and I don't know the complete list of column names in dt
, to avoid conflicts.
推荐答案
1.8.2 版的 NEWS 中有一项建议在某个时候添加 ..()
语法,允许这个
There is an item in the NEWS for 1.8.2 that suggests a ..()
syntax will be added at some point, allowing this
新的 DT[.(...)] 语法(以包 plyr 的风格)与DT[list(...)]、DT[J(...)] 和 DT[data.table(...)].我们也计划添加 ..() ,所以.() 和 ..() 类似于文件系统的 ./和 ../;IE., .()在父作用域中的 DT 和 ..() 框架内计算.
New DT[.(...)] syntax (in the style of package plyr) is identical to DT[list(...)], DT[J(...)] and DT[data.table(...)]. We plan to add ..(), too, so that .() and ..() are analogous to the file system's ./ and ../; i.e., .() evaluates within the frame of DT and ..() in the parent scope.
同时,你可以从合适的环境get
In the mean time, you can get
from the appropriate environment
dt[J(get('x', envir = parent.frame(3)))]
## x y
## 1: 3 5
## 2: 4 6
或者你可以 eval
对 list(x)
或 J(x)
or you could eval
the whole call to list(x)
or J(x)
dt[eval(list(x))]
dt[eval(J(x))]
dt[eval(.(x))]
这篇关于在没有“with"的情况下对 data.table 进行键控查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!