1) Firstly note that
search_value <- c("setosa", 5.0)
will coerce 5.0 to character so this is problematic. Instead create a data frame and then use inner_join
.
(If the search_value were all strings and not a mix of strings and numerics then in terms of the variables shown in the question we could use the commented out line or we could just use search_cols in place of names(searchDF) below and use search_value in place of searchDF elsewhere.)
# searchDF <- as.data.frame(setNames(as.list(search_value), search_col))
searchDF <- data.frame(Species = "setosa", Sepal.Length = 5.0)
inner_join(iris, searchDF, by = names(searchDF))
giving:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5 3.6 1.4 0.2 setosa
2 5 3.4 1.5 0.2 setosa
3 5 3.0 1.6 0.2 setosa
4 5 3.4 1.6 0.4 setosa
5 5 3.2 1.2 0.2 setosa
6 5 3.5 1.3 0.3 setosa
7 5 3.5 1.6 0.6 setosa
8 5 3.3 1.4 0.2 setosa
2) If you must use filter
then use cur_data()
to refer to the data. The scalar variable can be used directly.
filter(iris, cur_data()[, names(searchDF)[1]] == searchDF[[1]] &
cur_data()[, names(searchDF)[2]] == searchDF[[2]])
3) For an arbitrary number of conditions use reduce
(from purrr) or Reduce
(from base R).
library(dplyr)
library(purrr)
myfilter <- function(x, nm) filter(x, cur_data()[, nm] == searchDF[[nm]])
iris %>% reduce(names(searchDF), myfilter, .init = .)