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

You could use subset() and [ as well. Here are some different methods and their respective benchmarks on a larger data set.

df <- expand.grid(A = 1:100, B = 1:100, C = 1:100)
df$value <- 1:nrow(df)

library(dplyr); library(microbenchmark)
f1 <- function() subset(df, A == 1 & B == 3 | A == 3 & B == 2)
f2 <- function() filter(df, A == 1 & B == 3 | A == 3 & B == 2)
f3 <- function() df[with(df, A == 1 & B == 3 | A == 3 & B == 2), ]
f4 <- function() df[(df$A == 1 & df$B == 3) | (df$A == 3 & df$B == 2),]

microbenchmark(subset = f1(), filter = f2(), with = f3(), "$" = f4())
# Unit: milliseconds
#    expr      min       lq     mean   median       uq      max neval
#  subset 47.42671 49.99802 75.95385 92.24430 96.05960 141.2964   100
#  filter 36.94019 38.77325 60.22831 42.64112 84.35896 155.0145   100
#    with 38.90918 44.36299 71.29214 86.39629 88.89008 134.7670   100
#       $ 40.22723 44.08606 71.32186 86.71372 89.59275 133.1132   100

dplyr solution:

load library:

library(dplyr)

filter with condition as above:

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

Tags:

R

Dplyr