1

I would like to filter a dataframe df based on some filter_phrase using quasiquotation (similar to this question here). However, instead of dynamically setting the column, I would like to evaluate the entire condition:

library(dplyr)
library(rlang)
df <- data.frame(a = 1:5, b = letters[1:5])
filter_phrase <- "a < 4"
df %>% filter(sym(filter_phrase))

The expected output should look like this:

> df %>% filter(a < 4)
  a b
1 1 a
2 2 b
3 3 c

Any help is greatly appreciated.

Ben Nutzer
  • 1,082
  • 7
  • 15

1 Answers1

2

An option would be parse_expr. The 'filter_phrase' is an expression as a string. We can convert it to langauge class with parse_expr and then evaluate with (!!)

library(dplyr)    
df %>%
     filter(!! rlang::parse_expr(filter_phrase))
#  a b
#1 1 a
#2 2 b
#3 3 c
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks, that is perfect! Problem solved :-) Do you mind elaborating a bit on what is happening in your code? – Ben Nutzer Sep 13 '19 at 17:38
  • 1
    @BenNutzer Also, if the intial obect is a language class (with `quo`) i.e. `filter_phrase <- quo(a < 4); df %>% filter(!!filter_phrase)` – akrun Sep 13 '19 at 17:44