I have a general question about the or and and operators in R.
In the below example, I am assigning a value to 2 variables x
and y
and Im just doing some logical operations on them. But when I wrap the expression in parenthesis, the result changes... and I'm wondering why or what is the logic behind this? For example:
x = 10
y = 2
# x or y is equal to 2
>x|y == 2
[1] TRUE
But when I add parenthesis:
> (x|y) == 2
[1] FALSE
Additionally, if I just check the x
:
> x|x == 2
[1] TRUE
> (x|x) == 2
[1] FALSE
Similarily for &
:
> x&y == 2
[1] TRUE
> (x&y)==2
[1] FALSE
I know this might be a basic question, but the logic behind this isn't as intuitive as I originally thought! I know there are lots of resources online talking about these operators.. but none of them seem to answer this type of question directly. I was wondering what is exactly going on here?
CodePudding user response:
The reason relates to conversion of non-zero values to TRUE and zero to FALSE
> as.logical(x)
[1] TRUE
> as.logical(0)
[1] FALSE
When we use |
(OR), it checks whether any of the elements are non-zero, and thus returns TRUE, whereas in &
, both elements should be non-zero
> x|y
[1] TRUE
and when we compare with 2
, it is not equal because the lhs is logical, when coerced to 1 (binary values correspond to TRUE/FALSE for 1/0), and rhs is 2
> (x|y) == 2
[1] FALSE
> (x|y) == 1
[1] TRUE
In addition, there is operator precedence when we don't wrap them inside brackets
x&(y == 2)
[1] TRUE
It returns TRUE because x
is non zero, and y ==2
returns TRUE, thus both returns TRUE
> y==2
[1] TRUE