Reputation: 4836
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
.
Upvotes: 1
Views: 53
Reputation: 193517
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
Upvotes: 6
Reputation: 886978
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
Upvotes: 3