如何过滤具有多个条件的数据框? [英] How to filter dataframe with multiple conditions?

查看:13
本文介绍了如何过滤具有多个条件的数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数据框,我想对其进行子集化(如果可能,使用 dplyrbase 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 大于 15 的 df$ 值x == 1,以及 df$x == 2 大于 5 的 df$y 值?

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屋!

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