I have a function which takes a character vector with variable names and an index which determines which of the variables is chosen as input for a dplyr::filter(). I have a very clunky way of extracting the variable I need for my filter call (see my approach below). However, I think there is a more concise way, and I am just not seeing it at the moment.
Any help appreciated.
library(dplyr)
myfilter <- function(data, filter_vec, filter_idx) {
# this part here is too verbose ----
filter_var <- data %>%
select(all_of(filter_vec)) %>%
select(all_of(filter_idx)) %>%
colnames
# ------
data %>%
filter(!! sym(filter_var) == 1)
}
# this function call uses the forth variable `am` as filter variable
mtcars %>%
myfilter(c("mpg", "cyl", "gear", "am"), 4)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
#> Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
#> Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
#> Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
#> Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
#> Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
#> Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
#> Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
#> Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
#> Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
#> Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
Created on 2020-10-30 by the reprex package (v0.3.0)