我希望在我的函数中使用dplyr
库的filter
和summarise
函数。如果不使用函数,代码如下:
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 和 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