broccoli
broccoli

Reputation: 4836

Filtering rows by a criteria defined by variables

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

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

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

akrun
akrun

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

Related Questions