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?
a == a
should work or is good syntax? R-forge seems to be down for me atm, so I can't see the link from @Arun and what exactly it's about, but makinga == a
work (in the way OP wants it to work) seems like a bad idea to me and I think your last solution is the correct one.data.table
is keyed bya
, you can dodt[a]