Subsetting data.table using variables with same name as column

为君一笑 提交于 2019-11-26 09:12:03

问题


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?


回答1:


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)
}



回答2:


Now it's simple (since ..() syntax introduced in data.table):

dt[eval(dt[, a %in% ..a])]

or even simpler in your particular case (since a is a 1st column):

dt[eval(.(a))] # identical to dt["b"]


来源:https://stackoverflow.com/questions/21658893/subsetting-data-table-using-variables-with-same-name-as-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!