2016-11-16 80 views
3

这可能有点不可思议,但在中使用其参数用于过滤的函数时,我经常遇到这种情况。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`] 
+1

相关信息[这里](HTTP: //stackoverflow.com/questions/15102068/keyed-lookup-on-data-table-without-with)和[这里](http://stackoverflow.com/questions/21658893/subsetting-data-table-using-variables -with-same-name-as-column) – Henrik

+0

@Henrik yup这些:) –

+0

@paljenczy那是因为通常和当然在r“过滤”被称为“子集”:) –

回答

4

Data.table在数据表本身的环境中运行的权利,所以你可能需要指定你想从

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

这是回答您的问题吗? –

3

只要指定范围界定:

DT[cyl == globalenv()$cyl]