data.table中的变量用法 [英] variable usage in data.table
问题描述
这一定是非常基本的事情,但是我不知道如何使用与data.table列同名的实型变量。我可以使用其他变量名称来避免冲突,但是我想知道是否有一种方法可以在放弃DT之前对变量进行评估。
It must be very basic thing but I can't figure out how to use a real variable that has the same name as a data.table column. I can use a different variable name to avoid conflict but I'm wondering if there's a way to eval the variable before giving up to DT.
> DT = data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c=13:18)
> DT
ID a b c
1: b 1 7 13
2: b 2 8 14
3: b 3 9 15
4: a 4 10 16
5: a 5 11 17
6: c 6 12 18
> DT[b == 7]
ID a b c
1: b 1 7 13
> b <- 7
> DT[b == b]
ID a b c
1: b 1 7 13
2: b 2 8 14
3: b 3 9 15
4: a 4 10 16
5: a 5 11 17
6: c 6 12 18
推荐答案
由于您有两个名为 b
的变量,其中一个在 DT
中,并且一个在 DT
范围之外的地方,我们必须从全球环境中获取 b< -7
。我们可以使用 get()
。
Since you have two variables named b
, one inside DT
and one outside the scope of DT
, we have to go and get b <- 7
from the global environment. We can do that with get()
.
DT[b == get("b", globalenv())]
# ID a b c
# 1: b 1 7 13
更新:您在注释中提到变量位于函数环境中。在那种情况下,您可以使用 parent.frame()
代替 globalenv()
。
Update: You mention in the comments that the variables are inside a function environment. In that case, you can use parent.frame()
instead of globalenv()
.
f <- function(b, dt) dt[b == get("b", parent.frame(3))]
f(7, DT)
# ID a b c
# 1: b 1 7 13
f(12, DT)
# ID a b c
# 1: c 6 12 18
这篇关于data.table中的变量用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!