bho*_*lly 5 r dplyr tidyeval rlang
我知道如何为名为“variable”的参数创建支持准引用的函数 {using dplyr::enquo(variable)for unquoted function arguments} 或需要您引用参数 {using rlang::sym("variable")}的函数。有没有一种简单的方法可以使函数支持带引号和不带引号的参数?
例如,dplyr::select()允许select(mtcars, mpg)和select(mtcars, "mpg")。构建可以执行任何操作的函数的最佳实践是什么?一个考虑因素是对数据屏蔽的影响,我不确定在构建更复杂的功能时是否需要考虑这一点。
我一直在浏览基本 dplyr 函数的 github 页面,但是像 select 这样的简单函数依赖于一个全新的包 (tidyselect),所以有很多事情要做。我在Tidy评测书中也没有看到明确的解释。下面是一个支持带引号和不带引号的参数的 hack 函数,但这不是一个可靠的解决方案。我相信有更简单的方法。
library(dplyr)
data(mtcars)
test_func <- function(variable) {
if(nrow(count(mtcars, {{variable}})) == 1) {
variable <- rlang::sym(variable)
}
count(mtcars, {{variable}})
}
all_equal(
test_func(cyl),
test_func("cyl")
)
Run Code Online (Sandbox Code Playgroud)
如果它需要同时处理引用/未引用,请使用 ensym
test_func <- function(variable) {
dplyr::count(mtcars, !!rlang::ensym(variable))
}
Run Code Online (Sandbox Code Playgroud)
-测试
test_func(cyl)
# cyl n
#1 4 11
#2 6 7
#3 8 14
test_func('cyl')
# cyl n
#1 4 11
#2 6 7
#3 8 14
Run Code Online (Sandbox Code Playgroud)
注意:最好将数据也作为函数的参数