功能问题.Tidyeval过滤

wil*_*031 0 r function dplyr nse tidyeval

这有什么不对?这有效:

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

并生产:

    msl   msw
1 5.006 0.246
Run Code Online (Sandbox Code Playgroud)

但是这个功能不起作用:

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

means(iris, "setosa")产生此错误:

UseMethod("filter_")中的错误:"filter_"的适用方法没有应用于类"c"(quosure','formula')的对象"来自:filter _(.data,.dots = compat_as_lazy_dots(...) ))

小智 5

错误消息非常简单,您无法过滤quosure.我不知道你为什么要输入你的数据,但这会得到你想要的东西:

means <- function(data, value){

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

}
Run Code Online (Sandbox Code Playgroud)