filter verb to take list arguments

Hi RStudio community,

this is my first and I try my best to describe the problem I have so please be gentle :slight_smile:

Aim: fill an empty tibble via a sequence of calls to dplyr::filter() where the arguments to this function call are provided from a list.

The list elements may be char or numeric and all of the same length.

Given what I have read in this post:

what I came up with so far is this (and I do hope I did the repex right...):


foo <- function(x, ...) {
args_quo <- rlang::quos(...)
filter(x, !!! args_quo)

my_cyl_values <- c(6, 8, 4)
my_carb_values <- c(4, 3, 1)

my_list_variables <- list(cyl = my_cyl_values, carb = my_carb_values)
len_filter <- length(my_list_variables[[1]])

data <- tibble(cyl = numeric(0), carb = numeric(0))

for (i in 1:len_filter) {
data_temp <- mtcars %>% foo(cyl == my_cyl_values[i], carb == my_carb_values[i])
data <- rbind(data, data_temp)

#> ─ Session info ──────────────────────────────────────────────────────────
#> setting value
#> version R version 3.5.1 (2018-07-02)
#> os Linux Mint 19
#> system x86_64, linux-gnu
#> ui X11
#> language en_US
#> collate en_US.UTF-8
#> ctype en_US.UTF-8
#> tz Europe/Paris
#> date 2019-05-06

Now, the next step is to make this part nicer:
data_temp <- mtcars %>% foo(cyl == my_cyl_values[i], carb == my_carb_values[i])

Currently, a call to foo() provides the arguments manually i.e. the user has to specify cyl == ..., carb ==... herself.

This does not work for arbitrary lists of the same structure as "my_list_values" but with varying list elements/names.

What I mean by "the same structure as 'my_list_val'" is what I wrote in the beginning:

Arbitray list-length and names, but all elements of the list having the same size (so I can effectively loop over them, as above) and of type "char" or "numeric" (so the comparison with "==" makes sense).

I did look at the related post here

but I did not understood the answer and felt there must be an easier way....

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.