Reputation: 696
Is there a way to use a string variable as the filter argument in dplyr? For example:
filter(iris,Sepal.Length > 6)
would be replaced with
string <- 'Sepal.Length > 6'
filter(iris,string)
Basically, I am looking for the entire filter string to be a variable as I am creating the filter string pragmatically. Thanks for any help.
Upvotes: 9
Views: 6262
Reputation: 10383
This is the only way I have found that works in the new tidyval:
> s = "A<3"
> data.frame(A=1:10, B=1:10) %>% filter(eval(str2expression(s)))
A B
1 1 1
2 2 2
However, I have not figured out how to do this with multiple conditions.
Upvotes: 4
Reputation: 99331
If you want to filter with a string argument, you'll need to use filter_()
instead of filter()
string <- 'Sepal.Length > 6'
filter_(iris, string)
Also note that it's recommended to use the *_()
functions when programming.
Upvotes: 17