Steve
Steve

Reputation: 655

why does this code using == and | operators result in TRUE

Why does this return TRUE:

15 == 1|2|10

I thought it would be asking is 15 the same as 1 or 2 or 10 which would result in FALSE.

Upvotes: 1

Views: 47

Answers (1)

MrFlick
MrFlick

Reputation: 206401

If you look at how R parses code, this

15 == 1|2|10

is the same as

(((15 == 1) | 2) | 10)

Where | will return TRUE if one of the values is not FALSE (or 0). So 15==1 is FALSE but FALSE | 2 is TRUE since 2 is not 0. And then TRUE | 10 is also TRUE. So

( FALSE | TRUE) | TRUE)  == TRUE

Do not use | to match one of multiple values. Use %in% to test if a value is contained in a vector of values.

15 %in% c(1, 2, 10)

Upvotes: 5

Related Questions