简体   繁体   English

逻辑运算符未按预期子集化

[英]Logical Operators not subsetting as expected

I am trying to create a subset of the rows that have a value of 1 for variable A, and a value of 1 for at least one of the following variables: B, C, or D. 我想创建具有变量A中的值为1的行的子集, 并且为1以下变量中的至少一个的值:B,C或D.

Subset1 <-  subset(Data,
              Data$A==1 &
                Data$B ==1  ||
                Data$C ==1 |
                Data$D == 1,
              select= A)
Subset1

The problem is that the code above returns some rows that have A=0 and I am not sure why. 问题是上面的代码返回了一些A = 0的行,但我不确定为什么。

To troublehsoot: 麻烦:

  1. I know that && and || 我知道&&|| are the long forms or and and or which vectorizes it. 是长格式or and 或or的长形式。 I have run this code several times using && , || 我已经使用&&||多次运行了此代码。 , & and | | in different places. 在不同的地方。 Nothing returns what I am looking for exactly. 什么都不会返回我正在寻找的确切信息。

  2. When I shorten the code, it works fine and I subset only the rows that I would expect: 当我缩短代码时,它可以正常工作,并且仅对我期望的行进行子集化:

Subset1 <- subset(Data, Data$A==1 & Data$B==0, select= A)

Subset1

Unfortunately, this doesn't suffice since I also need to capture rows whose C or D value = 1. Can anyone explain why my first code block is not subsetting what I am expecting it to? 不幸的是,这还不够,因为我还需要捕获C或D值= 1的行。有人可以解释为什么我的第一个代码块没有设置我期望的值吗?

You can use parens to be more specific about what your & is referring to. 您可以使用括号来更具体地了解&指的是什么。 Otherwise (as @Patrick Trentin clarified) your logical operators are combined according to operator precedence (within the same level of precedence they are evaluated from left to right). 否则(如@Patrick Trentin所阐明的那样),您的逻辑运算符将根据运算符优先级进行组合(在相同的优先级中,它们从左到右进行评估)。

Example: 例:

> FALSE & TRUE | TRUE #equivalent to (FALSE & TRUE) | TRUE
[1] TRUE
> FALSE & (TRUE | TRUE)
[1] FALSE

So in your case you can try something like below (assuming you want items that A == 1 & that meet one of the other conditions): 因此,在您的情况下,您可以尝试以下操作(假设您希望A == 1 &满足其他条件之一的项目):

Data$A==1 & (Data$B==1 | Data$C==1 | Data$D==1)

Since you didn't provide the data you're working with, I've replicated some here. 由于您未提供要使用的数据,因此我在这里复制了一些数据。

set.seed(20)
Data = data.frame(A = sample(0:1, 10, replace=TRUE),
                  B = sample(0:1, 10, replace=TRUE),
                  C = sample(0:1, 10, replace=TRUE),
                  D = sample(0:1, 10, replace=TRUE))

If you use parenthesis, which can evaluate to a logical function, you can achieve what you're looking for. 如果使用括号(可以评估为逻辑函数),则可以实现所需的功能。

Subset1 <- subset(Data,
                  Data$A==1 &
                    (Data$B == 1 |
                    Data$C == 1 |
                    Data$D ==1),
                  select=A)
Subset1
  A
1 1
2 1
4 1
5 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM