Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

r - Subsetting data.table using variables with same name as column

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...