如何筛选具有多个条件的数据框? [英] How to filter dataframe with multiple conditions?
本文介绍了如何筛选具有多个条件的数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对这个数据帧进行子集化(如果可能的话,请使用 dplyr
或 base R
函数):
I have this dataframe that I'll like to subset (if possible, with dplyr
or base R
functions):
df <- data.frame(x = c(1,1,1,2,2,2), y = c(30,10,8,10,18,5))
x y
1 30
1 10
1 8
2 10
2 18
2 5
假设x是因子(所以2个条件/级别),我如何子集/过滤此数据框,以便仅得到 df $ y的
,而 df $ y
值x == 1 df $ x == 2
的 df $ y
值是否大于5?
Assuming x are factors (so 2 conditions/levels), how can I subset/filter this dataframe so that I get only df$y
values that are greater than 15 for df$x == 1
, and df$y
values that are greater than 5 for df$x == 2
?
这就是我想要得到的:
df2 <- data.frame(x = c(1,2,2), y = c(30,10,18))
x y
1 30
2 10
2 18
感谢任何帮助!谢谢!
推荐答案
您可以尝试
with(df, df[ (x==1 & y>15) | (x==2 & y>5), ])
x y
1 1 30
4 2 10
5 2 18
或使用 dplyr
library(dplyr)
filter(df, (x==1 & y>15) | (x==2 & y>5))
这篇关于如何筛选具有多个条件的数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文