我是 tidy eval 的新手,并试图编写通用函数——我现在正在努力解决的一件事是为分类变量编写多个过滤条件。这就是我现在正在使用的-
create_expr <- function(name, val){
if(!is.null(val))
val <- paste0("c('", paste0(val, collapse = "','"), "')")
paste(name, "%in%", val)
}
my_filter <- function(df, cols, conds){
# Args:
# df: dataframe which is to be filtered
# cols: list of column names which are to be filtered
# conds: corresponding values for each column which need to be filtered
cols <- as.list(cols)
conds <- as.list(conds)
args <- mapply(create_expr, cols, conds, SIMPLIFY = F)
if(!length(args))
stop(cat("No filters provided"))
df <- df %>% filter_(paste(unlist(args), collapse = " & "))
return(df)
}
my_filter(gapminder, cols = list("continent", "country"),
conds = list("Europe", c("Albania", "France")))
我想知道如何使用整洁的评估实践来重写它。我找到了有关将 quos() 用于多个参数的材料,但正如您所见,我在这里有两个不同的参数列表,它们需要相互映射。
任何帮助表示赞赏,谢谢!