4

It must be very basic thing but I can't figure out how to use a real variable that has the same name as a data.table column. I can use a different variable name to avoid conflict but I'm wondering if there's a way to eval the variable before giving up to DT.

> DT = data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c=13:18)
> DT
   ID a  b  c
1:  b 1  7 13
2:  b 2  8 14
3:  b 3  9 15
4:  a 4 10 16
5:  a 5 11 17
6:  c 6 12 18
> DT[b == 7]
   ID a b  c
1:  b 1 7 13
> b <- 7
> DT[b == b]
   ID a  b  c
1:  b 1  7 13
2:  b 2  8 14
3:  b 3  9 15
4:  a 4 10 16
5:  a 5 11 17
6:  c 6 12 18
fatdragon
  • 2,211
  • 4
  • 26
  • 43
  • Well, there's `merge(DT,list(b=b))[]`. The trailing brackets are needed thanks to (what I assume is) a bug. – Frank Dec 03 '15 at 23:10
  • @Frank - Wouldn't it have to be `merge(DT, list(b=b), by="b")`? Your code gave me a key matching error. – Rich Scriven Dec 03 '15 at 23:19
  • @RichardScriven You're right -- oops. I had set the key while messing around trying to find a way for it to work. – Frank Dec 03 '15 at 23:40
  • thanks guys. looks like i'm better off creating a new variable than jumping through hoops :-) – fatdragon Dec 04 '15 at 07:36

1 Answers1

4

Since you have two variables named b, one inside DT and one outside the scope of DT, we have to go and get b <- 7 from the global environment. We can do that with get().

DT[b == get("b", globalenv())]
#    ID a b  c
# 1:  b 1 7 13

Update: You mention in the comments that the variables are inside a function environment. In that case, you can use parent.frame() instead of globalenv().

f <- function(b, dt) dt[b == get("b", parent.frame(3))] 

f(7, DT)
#    ID a b  c
# 1:  b 1 7 13
f(12, DT)
#    ID a  b  c
# 1:  c 6 12 18
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245