如何在r中的函数定义中正确使用dplyr动词? [英] How to correctly use dplyr verbs inside a function definition in r?
问题描述
我想使用过滤器
和总结
从 dplyr
我的功能内没有功能,它的工作方式如下:
I want to use filter
and summarise
from dplyr
inside my function. Without a function it works like following:
library(dplyr)
> Orange %>%
+ filter(Tree==1) %>%
+ summarise(age_max = max(age))
age_max
1 1582
我想在函数中做同样的事情,但是以下失败:
I want to do the same inside a function, but following fails:
## 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 和第2页。但是我不能完全把握NSE和SE的概念。我尝试以下操作:
I know that similar questions have been asked before. I've also gone through some relevant links such as page1 and page2. But I can't fully grasp the concepts of NSE and SE. I tried following:
df.maker <- function(df, plant, Age){
require(dplyr)
dfo <- df %>%
filter_(plant==1) %>%
summarise_(age_max = ~max(Age))
return(dfo)
}
但是得到同样的错误。请帮我理解发生了什么我如何正确地创建我的功能?谢谢!
But get the same error. Please help me understand what's going on. And how can I correctly create my function? Thanks!
编辑:
我也尝试过:
I also tried following:
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
或者用替换
:
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
这篇关于如何在r中的函数定义中正确使用dplyr动词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!