Yamazaki
Yamazaki

Reputation: 41

Combining & (AND) and | (OR) with a > comparison

OK, I guess this is really basic, but I'm confused by the results. Perhaps can someone explain to me how R interprets what I typed. I was just playing around in R, and I wanted to check if & and | worked as I expected them to, as "and" or "or". Here is what I tried:

x <- 1:10
y <- 7:-2
rbind(x, y, x&y>5, y&x>5, x|y>5)

This is what I got :

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
x    1    2    3    4    5    6    7    8    9    10
y    7    6    5    4    3    2    1    0   -1    -2
     1    1    0    0    0    0    0    0    0     0
     0    0    0    0    0    1    1    0    1     1
     1    1    1    1    1    1    1    1    1     1

So I understood my mistake, modified to "x>5 & y>5" and "x>5 | y>5", and got the results I would expect.

But can anybody explain to me what R understands with my initial input, and why x&y and y&x don't even give the same result! If someone was kind enough to point out what it means?..

Upvotes: 1

Views: 141

Answers (3)

Bathsheba
Bathsheba

Reputation: 234715

It's to do with operator precedence. > binds tighter than &.

So your computation is equivalent to x & (y > 5) which, in words means, x is non-zero and y is greater than 5.

Upvotes: 1

John Paul
John Paul

Reputation: 12664

x&y>5 is interpreted as x is not FALSE and y>5. Note that 0 will evaluate as FALSE .

Upvotes: 0

MrFlick
MrFlick

Reputation: 206243

Well, note that x&y and y&x do give the same results

all(x&y == y&x)
# [1] TRUE

the difference comes when you add the > part. This has to do with operator precedence in R. See the ?Syntax help page for the order of operations. It turns out that > has higher precedence than & so you're really doing

x&(y>5)
y&(x>5)

so you will get different results.

Upvotes: 0

Related Questions