I have a list named filter_vals which contains filter criteria for each column of the (subsetted) iris data set. Within this list it might happen that some entries are character(0). If this is the case I do not want to filter the corresponding column, however, still it should work when there is a filter criteria instead of character(0)
library(dplyr)
filter_vals = list(c(3,5), character(0), "setosa", character(0))
iris %>%
as_tibble() %>%
select(Sepal.Length, Sepal.Width, Species) %>%
mutate(x = "texttext") %>%
filter(between(Sepal.Length, filter_vals[[1]][1], filter_vals[[1]][2]),
# because filter_vals[[2]] is "character(0)" I dont want to apply a filtering on column Sepal.width, however, it might happen that filter_vals[[2]] = c(3,2)
# I think filtering wihtout filtering rows out could be achieved by filter(Sepal.Width %in% Sepal.Width)
Species %in% filter_vals[[3]],
# because filter_vals[[4]] is "character(0) I dont was to apply a filtering on column x, however, it might happen that filter_vals[[4]] = "textext"
)
The expected output for the given filter_vals should be this
# A tibble: 28 x 4
Sepal.Length Sepal.Width Species x
<dbl> <dbl> <fct> <chr>
1 4.9 3 setosa texttext
2 4.7 3.2 setosa texttext
3 4.6 3.1 setosa texttext
4 5 3.6 setosa texttext
5 4.6 3.4 setosa texttext
6 5 3.4 setosa texttext
7 4.4 2.9 setosa texttext
8 4.9 3.1 setosa texttext
9 4.8 3.4 setosa texttext
10 4.8 3 setosa texttext
# … with 18 more rows
For an other filter_vals it should look differently, see below:
filter_vals = list(c(3,5), c(1,3), "setosa", character(0))
iris %>%
as_tibble() %>%
select(Sepal.Length, Sepal.Width, Species) %>%
mutate(x = "texttext") %>%
filter(between(Sepal.Length, filter_vals[[1]][1], filter_vals[[1]][2]),
between(Sepal.Width, filter_vals[[2]][1], filter_vals[[2]][2]),
Species %in% filter_vals[[3]],
# because filter_vals[[4]] is "character(0) I dont was to apply a filtering on column x, however, it might happen that filter_vals[[4]] = "textext"
)
# A tibble: 8 x 4
Sepal.Length Sepal.Width Species x
<dbl> <dbl> <fct> <chr>
1 4.9 3 setosa texttext
2 4.4 2.9 setosa texttext
3 4.8 3 setosa texttext
4 4.3 3 setosa texttext
5 5 3 setosa texttext
6 4.4 3 setosa texttext
7 4.5 2.3 setosa texttext
8 4.8 3 setosa texttext
filter_valsthis is the expected output. However, if the firstcharacter(0)would be replaced for instance byc(3,4)the output should be differentfilter_vals. Are you doing the filtering based on those if they are not emptyfilter_vals = list(c(3,5), character(0), "setosa", character(0))which among them are forbetweenand which one is for second filter