使用与列名称相同的变量来设置data.table [英] Subsetting data.table using variables with same name as column
本文介绍了使用与列名称相同的变量来设置data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 data.table
子集化为一个变量,其名称与列出的问题相同:
dt b = sample(c('a','b','c'),20,replace = TRUE),
c = sample(20),key = c('a','b' )
evn< - environment()
a< - 'b'
dt [a == a]
#Expected结果
dt [a =='b']
我遇到了这是可能的解决方案:
env <-environment()
/ pre>
dt [a == get('a',env)]
但它是如此不现实:
a = a
dt [a == this.a]
解决方案
解决方案暂时的解决方案可能是
`..`< - function(...,.env = globalenv())
{
get(deparse ,env = .env)
}
..(a)
## [1]b
dt [a ==。 。(a)]
## abc
## 1:ba 15
## 2:ba 11
## 3:bb 8
## 4: bb 4
## 5:bc 5
## 6:bc 12
根据@ mnel的建议编辑,
`..`< - function(...,.env = sys.parent(2))
{
get deparse(substitute(...)),env = .env)
}
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']
I came across this possible solution:
env <- environment() dt[a == get('a',env)]
But it is as unhandy as:
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.
Edited according to @mnel's suggestion,
`..` <- function (..., .env = sys.parent(2)) { get(deparse(substitute(...)), env = .env) }
这篇关于使用与列名称相同的变量来设置data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文