Filter data.table using inequalities and variable column names

Viewed 4780

I have a data.table that i want to filter based on some inequality criteria:

dt <- data.table(A=letters[1:3], B=2:4)
dt
#    A B
# 1: a 2
# 2: b 3
# 3: c 4

dt[B>2]
#    A B
# 1: b 3
# 2: c 4

The above works well as a vector scan solution. But I can't work out how to combine this with variable names for the columns:

mycol <- "B"
dt[mycol > 2]
#    A B      // Nothing has changed
# 1: a 2
# 2: b 3
# 3: c 4

How do I work around this? I know I can use binary search by setting keys using setkeyv(dt, mycol) but I can't see a way of doing a binary search based on some inequality criteria.

3 Answers
Related