'How to pass dplyr `filter` a character vector as part of a function

I want to make a flexible regression function where I can feed a character string about what to subgroup into dplyr's filter function.

Here's the near-exact setup I'd like:

library(datasets)
data(iris)

reg_function <- 
  function(subgroup = NULL) {
    
    temp_df <- 
      iris %>% 
      filter(subgroup)
    
    lm(Sepal.Length ~ Petal.Width, data = temp_df)
    
  }

Then I'd like to run the function as follows:

out <- reg_function(subgroup = "Species == 'virginica'")

Obvious filter isn't happy with being passed the string. What can I do to make it recognize this as a valid argument?

(Note I really need this to be passed as a string to preserve flexibility for more complicated subgroups.)



Solution 1:[1]

filter() expects one or more expressions that return a logical value. You need to parse the character vector into an expression and then unquote it in filter (since filter is a data-masking function, see here).

my_filter <- function(df, expr) {
  expr <- rlang::parse_expr(expr)
  dplyr::filter(df, !!expr)
}

my_filter(iris, "Species == 'virginica'")
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MorganK95