当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 filter()用法及代码示例


filter()R语言中的函数用于选择案例并根据过滤表达式过滤掉值。

用法: filter(x, expr)

参数:
x:要过滤的对象
expr:作为过滤基础的表达式

范例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") ) 
d 
    
# Finding rows with NA value 
filter(d, is.na(ht)) 
    
# Finding rows with no NA value 
filter(d, ! is.na(ht)) 

输出:

     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

范例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") ) 
d 
    
# Finding rows with school
filter(d, school == "yes") 
    
# Finding rows with no school
filter(d, school == "no")  

输出:

     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



相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Filter Out the Cases from an Object in R Programming – filter() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。