使用与列同名的变量对 data.table 进行子集 [英] Subsetting data.table using variables with same name as column
本文介绍了使用与列同名的变量对 data.table 进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用一个与导致一些问题的列同名的变量对 data.table
进行子集化:
I want to subset a data.table
using a variable which has the same name as the column which leeds to some problems:
dt <- data.table(a=sample(c('a', 'b', 'c'), 20, replace=TRUE),
b=sample(c('a', 'b', 'c'), 20, replace=TRUE),
c=sample(20), key=c('a', 'b'))
evn <- environment()
a <- 'b'
dt[a == a]
#Expected Result
dt[a == 'b']
我遇到了这个可能的解决方案:
env <- environment()
dt[a == get('a',env)]
但它并不方便:
this.a = a
dt[a == this.a]
那么还有其他优雅的解决方案吗?
So is there another elegant solution?
推荐答案
目前,一个临时的解决方案可能是,
For now, a temporary solution could be,
`..` <- function (..., .env = globalenv())
{
get(deparse(substitute(...)), env = .env)
}
..(a)
## [1] "b"
dt[a==..(a)]
## a b c
## 1: b a 15
## 2: b a 11
## 3: b b 8
## 4: b b 4
## 5: b c 5
## 6: b c 12
虽然这看起来很优雅,但我仍在等待针对此类范围问题的更强大的解决方案.
Though this looks elegant, I am still waiting for a more robust solution to such scope issues.
根据@mnel 的建议编辑,
Edited according to @mnel's suggestion,
`..` <- function (..., .env = sys.parent(2))
{
get(deparse(substitute(...)), env = .env)
}
这篇关于使用与列同名的变量对 data.table 进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文