Search code examples
rfunctiondplyrnsetidyeval

Function issue. Tidyeval filtering


What is wrong here? This works:

iris %>% 
  filter(Species == "setosa") %>% 
  summarise(msl = mean(Sepal.Length), msw = mean(Petal.Width))

and produces:

    msl   msw
1 5.006 0.246

But this function doesn't work:

means <- function(data, value){
  data <- enquo(data)
  value <- enquo(value)
  data %>% 
    filter(Species == !!value) %>% 
    summarise(msl = mean(Sepal.Length), msw = mean(Petal.Width))
}

and means(iris, "setosa") produces this error:

Error in UseMethod("filter_") : no applicable method for 'filter_' applied to an object of class "c('quosure', 'formula')" Called from: filter_(.data, .dots = compat_as_lazy_dots(...))


Solution

  • The error message is pretty straightforward, you can't filter a quosure. I don't know why you are enquo'ing your data, but this will get you what you want:

    means <- function(data, value){
    
      value <- enquo(value)
      data %>% 
        filter(Species == !!value) %>% 
        summarise(msl = mean(Sepal.Length), msw = mean(Petal.Width))
    
    }