[英]filter row in data.table using object with same name as column
I have a data.table dt
with column names x
and y
.我有一个列名为
x
和y
的 data.table dt
。 I also have object y
that I need to use to filter some rows in dt
using the values in dt$y
.我还有 object
y
,我需要使用dt$y
中的值过滤dt
中的某些行。 Unfortunately, since one of the columns has the same name as the object, I can't make it work.不幸的是,由于其中一列与 object 同名,我无法使其工作。 What am I doing wrong?
我究竟做错了什么? Thank you so much.
太感谢了。
library(data.table)
dt <- data.table( x = c(1:4),
y = letters[1:4])
y <- "c"
dt[y == y]
#> x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d
dt[y == (y)]
#> x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d
dt[y == ..y]
#> Error in eval(stub[[3L]], x, enclos): object '..y' not found
eval(quote(y))
#> [1] "c"
dt[y == eval(quote(y))]
#> x y
#> 1: 1 a
#> 2: 2 b
#> 3: 3 c
#> 4: 4 d
Created on 2021-04-12 by the reprex package (v2.0.0)由代表 package (v2.0.0) 于 2021 年 4 月 12 日创建
PS: I apologize if this question has been asked somewhere else. PS:如果在其他地方问过这个问题,我深表歉意。 I searched for an answer, but I could not find it.
我搜索了一个答案,但我找不到它。
You could use get()
and the env
argument:您可以使用
get()
和env
参数:
dt[y == get('y', env = -2)]
# x y
# 1: 3 c
Beware this makes certain assumptions about your setup.请注意,这会对您的设置做出某些假设。 If your
y
is defined in the global environment as in your example, then a safer solution (as suggested by Ian Campell) would be:如果您的
y
像您的示例一样在全局环境中定义,那么更安全的解决方案(如 Ian Campell 所建议)将是:
dt[y == get('y', env = globalenv())]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.