使用rlang s sym在功能中并获取错误
我具有以下功能:
library(tidyverse)
library(dplyr)
library(rlang)
custom_filter <- function(
df,
pos_filter_1 = NULL,
ct_filter_1,
filter_1
){
pos_filter_1 <- paste0("df$", pos_filter_1)
position_filter_1 <- if (!is.null(pos_filter_1)) (match.fun(filter_1)(!!rlang::sym(pos_filter_1), ct_filter_1)) else TRUE
fin_df <- df %>%
dplyr::filter(position_filter_1)
return(fin_df)
}
但是,当我尝试在数据框架上使用它时,我会在!rlang :: Sym(pos_filter_1)中获得错误错误:无效参数类型
。这是一个示例,我尝试在行上过滤列qb_count
小于或等于5:
df <- tibble(x1 = letters[1:9],
qb_count = 1:9,
rb_count = 10:18)
custom_filter(df, 'qb_count', 5, "<=")
我缺少什么?如果我在功能之外进行操作,这很好。感谢任何帮助!
I have the following function:
library(tidyverse)
library(dplyr)
library(rlang)
custom_filter <- function(
df,
pos_filter_1 = NULL,
ct_filter_1,
filter_1
){
pos_filter_1 <- paste0("dfquot;, pos_filter_1)
position_filter_1 <- if (!is.null(pos_filter_1)) (match.fun(filter_1)(!!rlang::sym(pos_filter_1), ct_filter_1)) else TRUE
fin_df <- df %>%
dplyr::filter(position_filter_1)
return(fin_df)
}
However, when I try to use it on a dataframe, I get the error Error in !rlang::sym(pos_filter_1) : invalid argument type
. Here is an example in which I try to filter on rows in which the column qb_count
is less than or equal to 5:
df <- tibble(x1 = letters[1:9],
qb_count = 1:9,
rb_count = 10:18)
custom_filter(df, 'qb_count', 5, "<=")
What am I missing? This works fine if I do it outside of the function. Appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
或更轻松的选项,我们可以创建
,
如果/else 为-testing
而无需使用
检查/else
将代码包装在if_any/if_All (它应该与一个或多个列一起使用)并使用
any_vars
(如果不存在列,则不会评估)- 测试
We may create the
if/else
as-testing
Or an easier option without having to check with
if/else
is wrapping the code inif_any/if_all
(it should work with one or more columns) and usingany_vars
(if the column is not present, it wouldn't evaluate)-testing