我有一个函数,我想将一个函数传递给它。但是,我似乎无法使用 tidy_eval 上下文让它工作。
这里是一些数据:
df <- tribble(
~A, ~B,
"hi", "hello",
"bye", "later"
)
我希望能够像这样调用函数:
my_quoting_fn(df, A, str_detect(., pattern = "h*"))
第三个参数可以是任何不同的函数。
这是我第一次尝试编写函数:
my_quoting_fn <- function(df, col, func) {
func <- enquo(func)
expr <- quo_get_expr(func)
df %>%
pull({{col}}) %>%
eval(expr)
上面给出了错误:
Error in eval(., expr) : invalid 'envir' argument of type 'language'`
如果我尝试:
my_quoting_fn <- function(df, col, func) {
df %>%
pull({{col}}) %>%
{{func}}
我得到了错误
Error in stri_detect_regex(string, pattern, negate = negate, opts_regex = opts(pattern)) : object '.' not found
最佳答案
如果您将函数作为带有波浪号 (~
) 的公式传递,您可以使用 rlang::as_function()
。
my_quoting_fn <- function(df, col, func) {
func = as_function(func)
df %>%
pull({{col}}) %>%
func
}
my_quoting_fn(df, A, ~str_detect(., pattern = "h*"))
[1] TRUE TRUE
关于r - 使用 tidy_eval/rlang 上下文将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228055/