我想 在我的函数内部使用filter
and summarise
。dplyr
如果没有函数,它的工作方式如下:
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