I am trying to wrap dplyr::filter
within a function where when there is more than one filter
condition, then they are passed as a vector or list. See this minimal example:
filter_wrap <- function(x, filter_args) {
filter_args_enquos <- rlang::enquos(filter_args)
dplyr::filter(x, !!!filter_args_enquos)
}
When there is a single condition I can make it work:
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))
When I try to pass more than one condition I get a problem. I was expecting that the !!!
operator in the dplyr::filter
call would splice my arguments but given the error message I guess I am understanding it wrong.
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))
Using a list does change the error message:
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)
I don't want to use ...
as my function will have other arguments and I may want to use dots for something else.
How can I expand my filter_args
argument when passing it to dplyr::filter
?