【发布时间】:2019-04-16 06:38:27
【问题描述】:
我试图将dplyr::filter 包装在一个函数中,当有多个filter 条件时,它们将作为向量或列表传递。看这个最小的例子:
filter_wrap <- function(x, filter_args) {
filter_args_enquos <- rlang::enquos(filter_args)
dplyr::filter(x, !!!filter_args_enquos)
}
当有一个条件时,我可以使它起作用:
data(iris)
message("Single condition works:")
expected <- dplyr::filter(iris, Sepal.Length > 5)
obtained <- filter_wrap(iris, filter_args = Sepal.Length > 5)
stopifnot(identical(expected, obtained))
当我尝试通过多个条件时,我遇到了问题。我原以为 dplyr::filter 调用中的 !!! 运算符会拼接我的论点,但鉴于错误消息,我想我理解错了。
message("Multiple conditions fail:")
expected <- dplyr::filter(iris, Sepal.Length > 5, Petal.Length > 5)
obtained <- filter_wrap(iris, c(Sepal.Length > 5, Petal.Length > 5))
# Error in filter_impl(.data, quo) : Result must have length 150, not 300
# Called from: filter_impl(.data, quo)
stopifnot(identical(expected, obtained))
使用列表确实会改变错误信息:
obtained <- filter_wrap(iris, list(Sepal.Length > 5, Petal.Length > 5))
# Error in filter_impl(.data, quo) :
# Argument 2 filter condition does not evaluate to a logical vector
# Called from: filter_impl(.data, quo)
我不想使用...,因为我的函数会有其他参数,我可能想用点来做其他事情。
将filter_args 参数传递给dplyr::filter 时如何扩展它?
【问题讨论】: