This question was posted 6 years ago. dplyr
is now up to version 1.0.2. Yet this is still a great discussion and helped me immensely with with my problem. I wanted to be able to construct filters from columns, operators, and values that are all specified by variables in memory. Oh, and for an indeterminate number of filters!
Consider the following list where I specify the column, the operator, and the value for two filters:
myFilters =
list(
list(var = "color", op = "%in%", val = "blue"),
list(var = "value", op = "<=", val = 3)
)
From this list, I want to run:
dplyr::filter(color %in% "blue", value <= 3)
We can use lapply
on the list
above to create a list
of call
objects, force evaluation of the calls using the !!!
operator, and pass that to filter
:
library(dplyr)
df <- data.frame(
color = c("blue", "black", "blue", "blue", "black"),
value = 1:5)
result =
lapply(myFilters, function(x) call(x$op, as.name(x$var), x$val)) %>%
{filter(df, !!!.)}
...and Shazam!
> result
color value
1 blue 1
2 blue 3
That's a lot to absorb, so if it isn't immediately apparent what's happening, let me unpack it a bit. Consider:
var = "color"
op = "%in%"
val = "blue"
I'd want to be able to run:
filter(df, color %in% "blue")
and if I also have:
var2 = "value"
op2 = "<="
val2 = 3
I might want to be able to get:
filter(df, color %in% "blue", value <= 3)
The solution uses call
s, which are unevaluated expressions. (See Hadley's Advanced R book) Basically, make a list of call
object from variables, and then force evaluation of the calls using the !!!
operator when calling dplyr::filter
.
call1 = call(op, as.name(var), val)
Here is the value of call1
:
> call1
color %in% "blue"
Let's create another call
:
call2 = call(op2, as.name(var2), val2)
Put them in list:
calls = list(call1, call2)
and use !!!
to evaluate the list of calls prior to sending them to filter
:
result = filter(df, !!!calls)