R:将过滤条件列表传递到数据框中 [英] R: pass a list of filtering conditions into a dataframe

查看:55
本文介绍了R:将过滤条件列表传递到数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,例如:

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',....)

是否可以使用基数R或dplyr进行类似的操作

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?

输出应为

filter(dataframe, Symbol in 'ABM' & Growth > 1.2 & Yield within (2 3) & PE>3 &...)


推荐答案

Base R版本:

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

这篇关于R:将过滤条件列表传递到数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆