Open In App

Filter Out the Cases from an Object in R Programming – filter() Function

Improve
Improve
Like Article
Like
Save
Share
Report

filter() function in R Language is used to choose cases and filtering out the values based on the filtering expression.

Syntax: filter(x, expr)

Parameters:
x: Object to be filtered
expr: expression as a base for filtering

Example 1:




# R Program to filter cases
  
# Loading library
library(dplyr)
  
# Create a data frame with missing data  
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "yes", "no", "no") ) 
    
# Finding rows with NA value 
filter(d, is.na(ht)) 
    
# Finding rows with no NA value 
filter(d, ! is.na(ht)) 


Output:

     name age ht school
1    Abhi   7 46    yes
2 Bhavesh   5 NA    yes
3  Chaman   9 NA     no
4   Dimri  16 69     no
     name age ht school
1 Bhavesh   5 NA    yes
2  Chaman   9 NA     no
   name age ht school
1  Abhi   7 46    yes
2 Dimri  16 69     no

Example 2:




# R Program to filter cases
  
# Loading library
library(dplyr)
  
# Create a data frame 
d <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),  
                 age = c(7, 5, 9, 16),  
                 ht = c(46, NA, NA, 69), 
                 school = c("yes", "no", "yes", "no") ) 
    
# Finding rows with school
filter(d, school == "yes"
    
# Finding rows with no school
filter(d, school == "no")  


Output:

     name age ht school
1    Abhi   7 46    yes
2 Bhavesh   5 NA     no
3  Chaman   9 NA    yes
4   Dimri  16 69     no
    name age ht school
1   Abhi   7 46    yes
2 Chaman   9 NA    yes
     name age ht school
1 Bhavesh   5 NA     no
2   Dimri  16 69     no


Last Updated : 19 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads