我想在我的函数中使用来自filter和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 发布于 2017-01-23 16:24:25
提供字符参数并使用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
https://stackoverflow.com/questions/41810320
复制相似问题