Bangyou Bangyou - 2 months ago 8
R Question

How to use or/and in dplyr to subset a data.frame

I would like to subset a data.frame with a combination of or/and. This is my code using normal R function.

df <- expand.grid(list(A = seq(1, 5), B = seq(1, 5), C = seq(1, 5)))
df$value <- seq(1, nrow(df))

df[(df$A == 1 & df$B == 3) |
(df$A == 3 & df$B == 2),]


How could I convert them using filter function in dplyr package? Thanks for any suggestions.

Answer

dplyr solution:

load library:

library(dplyr)

filter with condition as above:

df %>% filter(A == 1 & B == 3 | A == 3 & B ==2)