Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

dplyr - R: pass a list of filtering conditions into a dataframe

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.85  
4     ADM  1.91 22.29      9.08  
5     ADP  2.46 25.83      8.57  
6     AFL  2.25  9.26      5.97  
7     ALB  1.44 13.53     13.15  
8    ANDE  1.02 19.59      5.74  
9     AOS  1.29 25.11      9.99  
10    APD  2.41 25.08      2.53  
11   ARLP  5.50 11.69      1.99  
12   AROW  3.83 14.68      1.01  
13  ARTNA  3.67 23.91      3.20  
14   ATNI  1.68  3.14      7.50  
15    ATO  2.97 18.59      1.72  

and a long list of boolean filtering conditions like

conditions = c('Symbol in `ABM', 'Growth > 1.2', 'Yield within (2 3)', 'PE>3',....)

Is there a way using base R or dplyr that I can do something like

for (condition in conditions) {    
cond = expression(condition)
    dataframe = dataframe[which(cond),]}

so that I can continually add to the condition list, instead of manually pasting them and using multiple &'s in the index?

The output should be

filter(dataframe, Symbol in 'ABM' & Growth > 1.2 & Yield within (2 3) & PE>3 &...)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...