使用不等式和变量列名过滤data.table

Mat*_*eck 15 inequality r data.table

我有一个data.table我想根据一些不平等标准过滤:

dt <- data.table(A=letters[1:3], B=2:4)
dt
#    A B
# 1: a 2
# 2: b 3
# 3: c 4

dt[B>2]
#    A B
# 1: b 3
# 2: c 4
Run Code Online (Sandbox Code Playgroud)

以上可以作为矢量扫描解决方案.但我无法弄清楚如何将其与列的变量名称结合起来:

mycol <- "B"
dt[mycol > 2]
#    A B      // Nothing has changed
# 1: a 2
# 2: b 3
# 3: c 4
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?我知道我可以通过设置密钥使用二进制搜索,setkeyv(dt, mycol)但我看不到根据一些不等式标准进行二进制搜索的方法.

Car*_*oft 11

好的,然后,使用get(mycol) 因为您希望参数为dt[对象"mycol"的内容.我相信dt[mycol ...]data.table物体本身中寻找一种"mycol" 物品,其中当然没有这种动物.


Sim*_*lon 5

为此提供了一个访问器功能。j在 的框架中计算X,即您的data.table除非您指定with = FALSE。这将是这样做的规范方式。

dt[ , mycol , with = FALSE ]
   B
1: 2
2: 3
3: 4
Run Code Online (Sandbox Code Playgroud)

返回列、逻辑比较、子集行...

dt[ c( dt[ , mycol , with = FALSE ] > 2 ) ]
Run Code Online (Sandbox Code Playgroud)


Mat*_*eck 5

另一种方法是使用以下]]方法检索B作为向量和子集:

dt[dt[[mycol]] > 2]
Run Code Online (Sandbox Code Playgroud)