Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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.

like image 932
Bangyou Avatar asked Jun 20 '14 04:06

Bangyou


People also ask

How does dplyr subset data?

In order to Filter or subset rows in R we will be using Dplyr package. Dplyr package in R is provided with filter() function which subsets the rows with multiple conditions on different criteria. We will be using mtcars data to depict the example of filtering or subsetting. Filter or subset the rows in R using dplyr.

Does dplyr work with data frame?

All of the dplyr functions take a data frame (or tibble) as the first argument. Rather than forcing the user to either save intermediate objects or nest functions, dplyr provides the %>% operator from magrittr.

What is the difference between subset and filter in R?

subset has a select argument. subset recycles its condition argument. filter supports conditions as separate arguments. filter preserves the class of the column.


1 Answers

dplyr solution:

load library:

library(dplyr)

filter with condition as above:

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

like image 89
npjc Avatar answered Sep 21 '22 20:09

npjc