Можно указать соответствующие столбцы с pmap
library(tidyverse)
pmap(list(c('Sepal.Length', 'Sepal.Width'), filter_vals[1:2], filter_vals[3:4]), ~
iris %>%
select(Species, ..1) %>%
transmute(ind = (if(length(..2) >0)
between(!! (rlang::sym(..1)), ..2[1], ..2[2]) else TRUE) &
(if(length(..3) >0) Species %in% ..3 else TRUE))) %>%
reduce(`&`) %>%
filter(iris, .)
. Его можно заключить в функцию
f1 <- function(data, filterLst1, filterLst2, varLst, otherCol) {
posbetween <- purrr::possibly(function(x, y, z)
between(x, y, z), otherwise = rep(TRUE, nrow(data)))
fin <- function(x, y) if(length(y) > 0) x %in% y else rep(TRUE, nrow(data))
pmap(list(varLst, filterLst1, filterLst2), ~
data %>%
dplyr::select(otherCol, ..1) %>%
dplyr::transmute(ind = posbetween((!! rlang::sym(..1)),
..2[1], ..2[2]) &
fin((!! rlang::sym(otherCol)), ..3))) %>%
reduce(`&`) %>%
filter(data, .) %>%
as_tibble
}
f1(iris, filter_vals[1:2], filter_vals[3:4],
c("Sepal.Length", "Sepal.Width"), "Species")
# A tibble: 28 x 5
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <fct>
# 1 4.9 3 1.4 0.2 setosa
# 2 4.7 3.2 1.3 0.2 setosa
# 3 4.6 3.1 1.5 0.2 setosa
# 4 5 3.6 1.4 0.2 setosa
# 5 4.6 3.4 1.4 0.3 setosa
# 6 5 3.4 1.5 0.2 setosa
# 7 4.4 2.9 1.4 0.2 setosa
# 8 4.9 3.1 1.5 0.1 setosa
# 9 4.8 3.4 1.6 0.2 setosa
#10 4.8 3 1.4 0.1 setosa
# … with 18 more rows
с измененным значением filter_vals.
filter_vals = list(c(3,5), c(1,3), "setosa", character(0))
f1(iris, filter_vals[1:2], filter_vals[3:4],
c("Sepal.Length", "Sepal.Width"), "Species")
# A tibble: 8 x 5
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <fct>
#1 4.9 3 1.4 0.2 setosa
#2 4.4 2.9 1.4 0.2 setosa
#3 4.8 3 1.4 0.1 setosa
#4 4.3 3 1.1 0.1 setosa
#5 5 3 1.6 0.2 setosa
#6 4.4 3 1.3 0.2 setosa
#7 4.5 2.3 1.3 0.3 setosa
#8 4.8 3 1.4 0.3 setosa