Filter or subsetting rows in R using Dplyr can be easily achieved. Dplyr package in R is provided with filter() function which subsets the rows with multiple conditions.
We will be using mtcars data to depict the example of filtering or subsetting.
Filter or subsetting the rows in R using Dplyr:
Subset using filter() function.
library(dplyr) mydata <- mtcars # subset the rows of dataframe with condition Mydata1 = filter(mydata,cyl==6) Mydata1
Only the rows with cyl =6 is filtered
Filter or subsetting the rows in R with multiple conditions using Dplyr:
library(dplyr) mydata <- mtcars # subset the rows of dataframe with multiple conditions Mydata1 = filter(mydata, gear %in% c(4,5)) Mydata1
The rows with gear=4 or 5 are filtered
Filter or subsetting the rows in R with multiple conditions (AND) using Dplyr
library(dplyr) mydata <- mtcars # subset the rows of dataframe with multiple conditions Mydata1 = filter(mydata, gear %in% c(4,5) & carb==2) Mydata1
The rows with gear= (4 or 5) and carb=2 are filtered
Filter or subsetting the rows in R with multiple conditions (OR) using Dplyr:
library(dplyr) mydata <- mtcars # subset the rows of dataframe with multiple conditions Mydata1 = filter(mydata, gear %in% c(4,5) | mpg==21.0) Mydata1
The rows with gear= (4 or 5) or mpg=21 are filtered
Filter or subsetting the rows in R with multiple conditions (NOT) using Dplyr:
library(dplyr) mydata <- mtcars # subset the rows of dataframe with multiple conditions Mydata1 = filter(mydata, !gear %in% c(4,5)) Mydata1
The rows with gear!=4 or gear!=5 are filtered
Filter or subsetting the rows in R with Contains condition using Dplyr:
library(dplyr) mydata <- mtcars # subset the rows of dataframe with multiple conditions Mydata1 = filter(mydata, grepl(0,hp)) Mydata1
hp which contains value 0 are filtered