Reputation: 76
I have a data frame which contains all the conditions.
cond.df = data.frame(
mpg = c(21,18.7,22.8),
gear = c(4,3,2),
carb = c(4,3,2)
)
So for my first output, I want a filtered data frame which is equivalent to
mtcars %>% filter(mpg == 21, gear == 4, carb = 4)
My desired output would be a list with n
data frames.
list(mtcars %>% filter(mpg == 21, gear == 4, carb = 4),
mtcars %>% filter(mpg == 18.7, gear == 3, carb = 3),
mtcars %>% filter(mpg == 22.8, gear == 2, carb = 2))
Also, if possible I want a solution for an unknown number of columns from cond.df
.
I am aware that if I only have one variable I can use %in%
, e.g.
mtcars %>% filter(gear %in% c(3,4))
However, I have more than one variable.
Thanks
Upvotes: 3
Views: 2030
Reputation: 311
I would propose to use an inner_join
of mtcars
on your cond.df
. This way, it can match on arbitrarily many variables in cond.df
.
I changed your conditions data frame a bit such that the second and third row actually match something.
library(dplyr)
cond.df = data.frame(
mpg = c(21,18.7,22.8),
gear = c(4,3,4),
carb = c(4,2,1)
)
This creates a dataframe with the filtered/joined dataframes in each row.
result <-
cond.df %>%
rowwise() %>%
do(
dfs = inner_join(as.data.frame(.), mtcars)
)
In case you need it as a list of dataframes, just convert it.
as.list(result)$dfs
Upvotes: 2
Reputation: 1
You can use apply to go over your cond.df row-wise, and then use an anonymous function to filter:
apply(cond.df,1, function(x) mtcars %>% # the 1 is for row wise
filter(mpg == x[1], gear == x[2], carb == x[3]))
Upvotes: 0