In dplyr
filter
, how to parse conditions which are stored in string?When there's only one condition, below code can work
library(dplyr)
conditions_string_1 <- "Species=='versicolor'"
iris %>% filter(eval(str2lang(conditions_string_1)))
But when there're two conditions, below code can't work. How to fix it?
conditions_string_2 <- "Species=='versicolor',Sepal.Width>3"
iris %>% filter(eval(str2lang(conditions_string_2)))
Just gsub
the comma to AND (&
) or OR (|
).
This assumes your column names or conditions don't contain comma.
conditions_string_2 <- "Species=='versicolor',Sepal.Width>3"
iris %>% filter(eval(str2lang(gsub(",", "&", conditions_string_2))))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 7.0 3.2 4.7 1.4 versicolor
2 6.4 3.2 4.5 1.5 versicolor
3 6.9 3.1 4.9 1.5 versicolor
4 6.3 3.3 4.7 1.6 versicolor
5 6.7 3.1 4.4 1.4 versicolor
6 5.9 3.2 4.8 1.8 versicolor
7 6.0 3.4 4.5 1.6 versicolor
8 6.7 3.1 4.7 1.5 versicolor