繁体   English   中英

data.table - 基于名称为列的变量的子集

[英]data.table - subsetting based on variable whose name is a column, too

这可能data.table在我使用其参数进行过滤的函数中使用data.table时,我经常遇到这种情况。

想象一下,您有一个变量,其值要与data.table的列进行比较并进行过滤。 如果变量的名称与列的名称相同怎么办?

我试过的例子和事情:

DT <- data.table(mtcars)
cyl <- 4
# intended: filter rows where column "cyl" equals the value of variable cyl

# this does not work
DT[cyl == (cyl)]
# this does not work either
DT[cyl == `cyl`]

Data.table在数据表本身的环境中运行,因此您可能需要指定从中获取值的位置

DT[cyl == get("cyl", envir = parent.frame())]

只需指定范围界定:

DT[cyl == globalenv()$cyl]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM