1

I've the following data.table

structure(list(val1 = c(1, 2, 1, 3, 4, 5, 3), val2 = c(4, 5, 6, 4, 2, 4, 5)), .Names = c("val1", "val2"), row.names = c(NA, -7L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0xedae28>)

What I would like to do is filter the rows in it based on a criteria defined by other variables. For example, I might want all rows that have val1 >= 1. This is easily done as

x[val1 > 1,]

However, I want to be able to specify the column name (i.e. either val1 or val2) as a variable and the filter value as a variable. I tried

cname = 'val1'
cutoff = 1
x[(cname >= cutoff),] # Try 1
x[(cname) >= (cutoff),] # Try 2
x[eval(cname > cutoff),] # Try 3

but it just gave back the original data.table.

zx8754
  • 52,746
  • 12
  • 114
  • 209
broccoli
  • 4,738
  • 10
  • 42
  • 54
  • List of related questions, though all of the answers are super long and/or don't use `get`, which is simplest: http://stackoverflow.com/q/24833247/1191259 – Frank Apr 29 '15 at 18:22
  • @Frank, you actually took the time to read through that linked question? :-) – A5C1D2H2I1M1N2O1R2T1 Apr 29 '15 at 18:24
  • @AnandaMahto Not quite, but more than I should have :) I had a feeling this was a dupe, but I like this Q&A much better than any of those. Here's my own question on the same thing: http://stackoverflow.com/q/19276194/1191259 I think everyone has asked this at some point. – Frank Apr 29 '15 at 18:29

2 Answers2

6

It sounds like you're looking for get:

x[get(cname) > cutoff,]
#    val1 val2
# 1:    2    5
# 2:    3    4
# 3:    4    2
# 4:    5    4
# 5:    3    5
dayne
  • 7,504
  • 6
  • 38
  • 56
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
3

You could use eval with as.name or as.symbol

x[eval(as.name(cname)) > cutoff]
#    val1 val2
#1:    2    5
#2:    3    4
#3:    4    2
#4:    5    4
#5:    3    5
akrun
  • 874,273
  • 37
  • 540
  • 662