r - 在函数中获取过滤器以进行整洁的评估

标签 r dplyr rlang

我正在尝试使用 dplyr 根据动态变量进行过滤。

我发现要让过滤器工作,我需要将变量名括在括号中。但是,如果我将它编程为一个函数,它就不能正常工作。

df_ex <- data.frame(a = 1:10, b = 11:20)

param <- quo(a)

# returns df_ex with column a, only, as expected
df_ex %>%
dplyr::select(!!param)

# returns expected df
df_ex %>%
dplyr::filter((!!param)==5)

# Now for the function
testfun <- function(test_df, filt_var){
   filt_var_mod <- quo(filt_var)

   test_df %>%
    dplyr::filter((!!filt_var_mod)==5)
}

# returns empty df, not as expected
testfun(df_ex, "a")

我想学习为自己找到这些问题类型的问题的答案,所以请随时向我推荐programming vignette 的相关部分。

最佳答案

如果您的函数接受列名作为字符,则无需引用它,另一方面,您需要将其转换为符号并在 filter 中评估它们立即使用 UQ!!nse语法:

testfun <- function(test_df, filt_var){
    test_df %>%
        dplyr::filter((!!rlang::sym(filt_var)) == 5)
}

testfun(df_ex, "a")
#  a  b
#1 5 15

如果要键入不带引号的列名,则需要 enquo , 其中

takes a symbol referring to a function argument, quotes the R code that was supplied to this argument, captures the environment where the function was called (and thus where the R code was typed), and bundles them in a quosure.

testfun <- function(test_df, filt_var){
    filt_var_mod <- enquo(filt_var)
    test_df %>%
        dplyr::filter((!!filt_var_mod) == 5)
}

testfun(df_ex, a)
#  a  b
#1 5 15

关于r - 在函数中获取过滤器以进行整洁的评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46964592/

相关文章:

r - 使用 tidyeval 进行编程回归建模

r - 将熔化操作从 tidyverse 转换为 data.table

r - 使用 knit 有条件地在 RMarkdown 中包含子文档列表

r - 将上面一行按下面一行划分

r - 错误 : The dbplyr package is required to communicate with database backends

r - 使用具有 mutate 函数的多个字符串的向量进行 Dplyr 标准评估

r - 如何计算 R quosure 中变量的数量?

r - 为什么需要两个随机偏差来确保使用 sample() 对大整数进行均匀采样?

r - 条形图上条形上方 ggplot 上的汇总统计量注释

r - 使用最大值改变 IF-Else 语句