简体   繁体   中英

dplyr filter: multiple conditions in a dataframe

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% , eg

mtcars %>% filter(gear %in% c(3,4))

However, I have more than one variable.

Thanks

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

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM