89_Simple
89_Simple

Reputation: 3805

filter rows based on multiple conditions

dat <- data.frame(id = c(0, 0, 01, 02, 03, 011, 012, 013, 0111, 0112, 0113),
                  x1 = rnorm(11), 
                  x2 = rnorm(11),
                  x3 = rnorm(11))


my.df <- data.frame(id = 0, id1 = 01, id2 = 011, id3 = 0111, some.column = 'xyz')

I want to filter rows from dat using following conditions:

If my.df$id3 is present in dat$id, filter dat$id == my.df$id3, if not check if my.df$id2 is present and filter dat$id == my.df$id2, if not, check if my.df$id1 is present and filter dat$id == my.df$id1, if not simply filter dat$id == my.df$id

dat %>% 
dplyr::filter(ifelse(my.df$id3 %in% id, id == my.df$id3, 
              ifelse(my.df$id2 %in% id, id == my.df$id2,
              ifelse(my.df$id1 %in% id, id == my.df$id1, id == my.df$id))))

It returns null rows.

Upvotes: 0

Views: 78

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389265

You can extract the column values in my.df the required order to create order_vec, filter values present in it, arrange the values and select the first row.

library(dplyr)

order_vec <- unlist(my.df[c(paste0('id', 3:1), 'id')])

dat %>%
  filter(id %in% order_vec) %>%
  arrange(match(id, order_vec)) %>%
  slice(1L)

#   id  x1    x2    x3
#1 111 1.5 0.872 0.848

Upvotes: 0

TimTeaFan
TimTeaFan

Reputation: 18581

Is this what you are looking for or how does your expected output look like? In the example below the filter id == my.df$id3 is applied if my.df$id3 is present in dat$id. Since this is the case, this filter leaves only one row of your original data.

library(dplyr)

dat <- data.frame(id = c(0, 0, 01, 02, 03, 011, 012, 013, 0111, 0112, 0113),
                  x1 = rnorm(11), 
                  x2 = rnorm(11),
                  x3 = rnorm(11))


my.df <- data.frame(id = 0, id1 = 01, id2 = 011, id3 = 0111, some.column = 'xyz')

dat %>% 
  dplyr::filter(if (my.df$id3 %in% id) {
                  id == my.df$id3
                } else if (my.df$id2 %in% id) {
                  id == my.df$id2
                } else if (my.df$id1 %in% id) {
                  id == my.df$id1 })
#>    id        x1         x2         x3
#> 1 111 0.3771992 -0.5073165 -0.3555985

Created on 2020-07-13 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions