如何在 r 的函数定义中正确使用 dplyr 动词?

How to correctly use dplyr verbs inside a function definition in r?

我想在我的函数中使用 dplyr 中的 filtersummarise。如果没有函数,它的工作方式如下:

library(dplyr)
> Orange %>% 
+     filter(Tree==1) %>% 
+     summarise(age_max = max(age))
  age_max
1    1582  

我想在一个函数中做同样的事情,但以下操作失败了:

## Function definition:

df.maker <- function(df, plant, Age){

  require(dplyr)

  dfo <- df %>% 
    filter(plant==1) %>% 
    summarise(age_max = max(Age))

  return(dfo)
}

## Use:
> df.maker(Orange, Tree, age)

 Rerun with Debug
 Error in as.lazy_dots(list(...)) : object 'Tree' not found

我知道以前有人问过类似的问题。我还浏览了一些相关链接,例如 page1 and page2。但是我不能完全掌握NSE和SE的概念。我试过以下:

df.maker <- function(df, plant, Age){

  require(dplyr)

  dfo <- df %>% 
    filter_(plant==1) %>% 
    summarise_(age_max = ~max(Age))

  return(dfo)
} 

但是得到同样的错误。请帮助我了解发生了什么。我怎样才能正确地创建我的功能?谢谢!

编辑:
我还尝试了以下操作:

df.maker <- function(df, plant, Age){

  require(dplyr)

  dfo <- df %>% 
    #filter_(plant==1) %>% 
    summarise_(age_max = lazyeval::interp(~max(x),
                                          x = as.name(Age)))

  return(dfo)
}  

> df.maker(Orange, Tree, age)
 Error in as.name(Age) : object 'age' not found 

要么提供字符参数,要么使用 as.name:

df.maker1 <- function(d, plant, Age){
  require(dplyr)
  dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = as.name(plant))) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = as.name(Age)))
  return(dfo)
}  
df.maker1(Orange, 'Tree', 'age')
  age_max
1    1582

或使用 substitute 捕获参数:

df.maker2 <- function(d, plant, Age){
  require(dplyr)
  plant <- substitute(plant)
  Age <- substitute(Age)

  dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = plant)) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = Age))
  return(dfo)
}  
df.maker2(Orange, Tree, age)
  age_max
1    1582