R: pass a list of filtering conditions into a dataframe

后端 未结 2 757
感情败类
感情败类 2020-12-17 07:00

I have a dataframe like:

   Symbol Yield    PE    Growth  
1    ABBV  3.46 18.80      5.00  
2     ABM  2.24 21.18      3.33  
3     ABT  2.26 23.65     10.8         


        
相关标签:
2条回答
  • 2020-12-17 07:10

    Base R version:

    conditions <- with(dat, list(Symbol %in% "ABM", Growth > 1.2, Yield > 2, Yield < 3, PE > 3))
    dat[Reduce(`&`, conditions ),]
    #  Symbol Yield    PE Growth
    #2    ABM  2.24 21.18   3.33
    
    0 讨论(0)
  • 2020-12-17 07:12

    Using dplyr

    library(dplyr)
    
    conditions = c('Symbol %in% "ABM"', 'Growth > 1.2', 'Yield > 2', 'Yield < 3', 'PE > 3')
    
    df %>% filter_(conditions)
    
    
      Symbol Yield    PE Growth
    1    ABM  2.24 21.18   3.33
    

    Data

    structure(list(Symbol = structure(1:15, .Label = c("ABBV", "ABM", 
    "ABT", "ADM", "ADP", "AFL", "ALB", "ANDE", "AOS", "APD", "ARLP", 
    "AROW", "ARTNA", "ATNI", "ATO"), class = "factor"), Yield = c(3.46, 
    2.24, 2.26, 1.91, 2.46, 2.25, 1.44, 1.02, 1.29, 2.41, 5.5, 3.83, 
    3.67, 1.68, 2.97), PE = c(18.8, 21.18, 23.65, 22.29, 25.83, 9.26, 
    13.53, 19.59, 25.11, 25.08, 11.69, 14.68, 23.91, 3.14, 18.59), 
        Growth = c(5, 3.33, 10.85, 9.08, 8.57, 5.97, 13.15, 5.74, 
        9.99, 2.53, 1.99, 1.01, 3.2, 7.5, 1.72)), .Names = c("Symbol", 
    "Yield", "PE", "Growth"), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
    "14", "15"))
    
    0 讨论(0)
提交回复
热议问题