Given an expression string in R, such as Species == 'setosa' & Petal.Length > 1.5, you can pass that expression through to a filter statement using !! in dplyr.
exp_string = rlang::parse_expr("Species == 'setosa' & `Petal.Length` > 1.5")
filtered_data <- iris |> filter(!!exp_string)
But when translating that to data.table, the filtering fails, complaining in a number of ways.
iris_dt <- setDT(copy(iris))
iris_dt[exp_string] # i has evaluated to type language
iris_dt[!!exp_string] # invalid argument type
So, what is the proper way to pass a filtering statement through to a data.table in R?
>Solution :
We may use eval – bang bang (!!) works only in the tidyverse environment, in all other cases, it is double negate (!)
iris_dt[eval(exp_string)]
-output
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1: 5.4 3.9 1.7 0.4 setosa
2: 4.8 3.4 1.6 0.2 setosa
3: 5.7 3.8 1.7 0.3 setosa
4: 5.4 3.4 1.7 0.2 setosa
5: 5.1 3.3 1.7 0.5 setosa
6: 4.8 3.4 1.9 0.2 setosa
7: 5.0 3.0 1.6 0.2 setosa
8: 5.0 3.4 1.6 0.4 setosa
9: 4.7 3.2 1.6 0.2 setosa
10: 4.8 3.1 1.6 0.2 setosa
11: 5.0 3.5 1.6 0.6 setosa
12: 5.1 3.8 1.9 0.4 setosa
13: 5.1 3.8 1.6 0.2 setosa