如何组合多个条件以使用“OR”来对数据帧进行子集 [英] How to combine multiple conditions to subset a data-frame using "OR"?

查看:106
本文介绍了如何组合多个条件以使用“OR”来对数据帧进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个data.frame。我想在两个不同的列上尝试两个不同的条件,但是我希望这些条件是包容性的。因此,我想使用或来组合条件。当我想使用AND条件时,我已经使用了以下语法,很多成功。

  my.data。帧<  -  data [(数据$ V1> 2)& (数据$ V2 <4),] 

但是我不知道如何使用' OR'在上面。

解决方案

  my.data.frame<  -  subset数据,V1> 2 | V2< 4)

函数,并且更适合包含在函数体内:

  new.data<  -  data [which(data $ V1 > 2 | data $ V2< 4),] 

有些人批评使用其中不需要,但它确实阻止了 NA 值抛出不需要的结果。对于上述两个选项,不使用 的等价物(.ie没有为V1或V2中的任何NA返回NA行):

  new.data<  -  data [(data $ V1> 2 | data $ V2< 4)& !is.na(V1 | V2),] 


I have a data.frame in R. I want to try two different conditions on two different columns, but I want these conditions to be inclusive. Therefore, I would like to use "OR" to combine the conditions. I have used the following syntax before with lot of success when I wanted to use the "AND" condition.

my.data.frame <- data[(data$V1 > 2) & (data$V2 < 4), ]

But I don't know how to use an 'OR' in the above.

解决方案

my.data.frame <- subset(data , V1 > 2 | V2 < 4)

An alternative solution that mimics the behavior of this function and would be more appropriate for inclusion within a function body:

new.data <- data[ which( data$V1 > 2 | data$V2 < 4) , ]

Some people criticize the use of which as not needed, but it does prevent the NA values from throwing back unwanted results. The equivalent (.i.e not returning NA-rows for any NA's in V1 or V2) to the two options demonstrated above without the which would be:

 new.data <- data[( data$V1 > 2 | data$V2 < 4) & !is.na(V1 | V2) , ]

这篇关于如何组合多个条件以使用“OR”来对数据帧进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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